0

I have that datetime : 2021-10-12T16:00:00.000+02:00 so I tried that :

import datetime
a = datetime.datetime.strptime("2021-10-12T16:00:00.000+02:00", '%Y-%m-%dT%H:%M:%SZ')

But it does not work I got that

ValueError: time data '2021-10-12T16:00:00.000+02:00' does not match format '%Y-%m-%dT%H:%M:%SZ'

Could you help me please ?

Thank you very much !

FObersteiner
  • 16,957
  • 5
  • 24
  • 56
John
  • 37
  • 2
  • 1
    Does this answer your question? [How to convert a timezone aware string to datetime in Python without dateutil?](https://stackoverflow.com/questions/13182075/how-to-convert-a-timezone-aware-string-to-datetime-in-python-without-dateutil) – Gino Mempin Oct 12 '21 at 10:28

3 Answers3

3

This is an ISO date. The easiest way to parse it is to call fromisoformat.

>>> datetime.datetime.fromisoformat("2021-10-12T16:00:00.000+02:00")       
datetime.datetime(2021, 10, 12, 16, 0, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200)))
BoarGules
  • 15,507
  • 2
  • 28
  • 42
1
import datetime
a = datetime.datetime.strptime("2021-10-12T16:00:00.000+02:00", '%Y-%m-%dT%H:%M:%S.%f%z')

You're formatting it wrong.

  1. You have milliseconds too, so there is a %f separated by a .
  2. The time zone is formatted as Z; it has to be %z
9769953
  • 7,301
  • 3
  • 20
  • 30
MSH
  • 1,428
  • 2
  • 13
  • 17
-2
from datetime import datetime
today=datetime.now() /// 2021-06-25 07:58:56.550604
dt_string = now.strftime("%d/%m/%Y %H:%M:%S") /// 25/06/2021 07:58:56
ZygD
  • 10,844
  • 36
  • 65
  • 84