2

I am trying to convert the following string to datetime in python. After referring to datetime.strptime(‘2017-01-12T14:12:06.000-0500’,'%Y-%m-%dT%H:%M:%S.%f%Z') I am trying the below mentioned format.

config_current_ts = datetime.strptime(internal_config["timestamp_str"], "%Y:%m:%dT%H:%M:%S.%f%z")

Yet I get an error stating :

ValueError: time data '2021-01-18T11:18:10.833876+00:00' does not match format '%Y:%m:%dT%H:%M:%S.%f%z'

I am using python3.7.4. Can someone tell me how to convert this to datetime? I want to basically compare the string and current time to see which is ahead.

Rekha R
  • 131
  • 1
  • 1
  • 12

2 Answers2

6

With Python 3.7+, use fromisoformat - since you have ISO 8601 format, it is appropriate and as a benefit also more efficient. Ex:

from datetime import datetime
s = '2021-01-18T11:18:10.833876+00:00'
dt = datetime.fromisoformat(s)

print(dt)
# 2021-01-18 11:18:10.833876+00:00
print(repr(dt))
# datetime.datetime(2021, 1, 18, 11, 18, 10, 833876, tzinfo=datetime.timezone.utc)
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
0

the format string should be '%Y-%m-%dT%H:%M:%S.%f%z'

>>> from datetime import datetime
>>> d = '2021-01-18T11:18:10.833876+00:00'
>>> datetime.strptime(d, '%Y-%m-%dT%H:%M:%S.%f%z')
datetime.datetime(2021, 1, 18, 11, 18, 10, 833876, tzinfo=datetime.timezone.utc)
buran
  • 13,682
  • 10
  • 36
  • 61