Computer >> Computer tutorials >  >> Programming >> Javascript

How to convert a JS Date to a Python date object?


You'll majorly want to convert a Javascript date to a Python date object when you send it over a network connection like an AJAX request or an IPC message(on nodejs). This representation will be in string format and you can choose to send it in any format you like. You can use the strptime function to parse the string back to a Python date object. There are standardized ways like ISO 8061 to send and receive date and time objects. In this case if we consider a simple example, it'll be a little easier to understand. 

Example

import datetime
# The string that you get from Javascript
date_string = '2017-12-31'
date_format = '%Y-%m-%d'
try:
  date_obj = datetime.datetime.strptime(date_string, date_format)
  print(date_obj)
except ValueError:
  print("Incorrect data format, should be YYYY-MM-DD")

Output

This will give the output:

2017-12-31 00:00:00

You can use many other directives to parse the date. Following are the directives supported by strptime()'s format string.

Directive    
Meaning
%a
Locale's abbreviated weekday name.      
%A
Locale's full weekday name.
%b
Locale's abbreviated month name.
%B  
Locale's full month name.
%c
Locale's appropriate date and time representation.
%d
Day of the month as a decimal number [01,31].  
%H
Hour (24-hour clock) as a decimal number [00,23].
%I
Hour (12-hour clock) as a decimal number [01,12].
%j
Day of the year as a decimal number [001,366].  
%m
Month as a decimal number [01,12].
%M
Minute as a decimal number [00,59].
%p
Locale's equivalent of either AM or PM.
%S
Second as a decimal number [00,61].
%U  
Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.
%w
Weekday as a decimal number [0(Sunday),6].  
%W
Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.
%x
Locale's appropriate date representation.
%X  
Locale's appropriate time representation.
%y
Year without century as a decimal number [00,99].  
%Y
Year with century as a decimal number.      
%Z
Time zone name (no characters if no time zone exists).  
%%
A literal "%" character.