Home > Software design >  Convert ISO 8061 datetime to timestamp in python
Convert ISO 8061 datetime to timestamp in python

Time:07-13

I have a string with a date in the format: 2021-03-12T14:45:34.000Z

I would like to convert it to a standard format as this one: 12-Mar-2021 14:45:34

I tried using:

print(datetime.datetime.strptime("2021-03-12T14:45:34.000Z", "%Y-%m-%dT%H:%M:%S%fZ"))

but I get the error:

ValueError: time data '2021-03-12T14:45:34.000Z' does not match format '%Y-%m-%dT%H:%M:%S%fZ'

How can I solve it?

CodePudding user response:

You are missing a . in your format string. The correct format string is

"%Y-%m-%dT%H:%M:%S.%fZ"

Notice the . after %S and before %fZ.

CodePudding user response:

You need to get as datetime then convert to forrmat as you like:

import datetime

date = '2021-03-12T14:45:34.000Z'

datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S.%fZ"
                 ).strftime('%d-%b-%Y %H:%M:%S')

Output:

'12-Mar-2021 14:45:34'
  • Related