0

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?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Babbara
  • 448
  • 1
  • 6
  • 21
  • Does this answer your question? [How do I parse an ISO 8601-formatted date?](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date) – FObersteiner Jul 12 '22 at 17:29
  • If you use a literal Z in your parsing directive, make sure to be aware of the difference between naive and aware datetime in Python. – FObersteiner Jul 12 '22 at 17:30

2 Answers2

2

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'
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
1

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.