0

Is there any method to convert date from "dd Mon yyyy" to "yyyy-mm-ddTHH:MM:SSZ" format in python?

For Example: Convert "17 Jan 2020" to "2020-01-17T00:00:00.000Z" format.

I have tried datetime.strftime() but I am not able to handle the input date format.

Simran
  • 98
  • 6
  • PIease post a [MRE](https://stackoverflow.com/help/minimal-reproducible-example) with code for assistance. – etch_45 Dec 24 '20 at 17:26

2 Answers2

2

Hope this quickly helps!

from datetime import datetime
d = datetime.strptime("17 Jan 2020", '%d %b %Y')
print(d)

The output is:

2020-01-17 00:00:00
srishtigarg
  • 1,106
  • 10
  • 24
0

strftime() expects a date object, so the string will need to be converted to a date object before it can be altered by strftime().

Use datetime.strptime() to convert a string to a date object: it uses the same syntax as strftime to identify the datetime elements of the input string. In the case of "17 Jan 2020", that process would look like this:

from datetime import datetime

datetime_string = "17 Jan 2020"
datetime_object = datetime.strptime(datetime_string, '%d %b %Y')

print(datetime_object.date())  # a datetime object

formatted_string_output = datetime.strftime(datetime_object, '%Y-%m-%dT%H:%M:%S.%fZ')

Note that %f will output 6 digits (microseconds, not milliseconds): use something like the solution suggested here to tailor your output to match your needs.

epopisces
  • 111
  • 2
  • 6