Akshay Bhat
Akshay Bhat

Reputation: 236

Unable to convert string to date time in python

I am trying the below piece of code and though the format seems to be correct, it seems to throw an error:

from datetime import datetime

utc_time1 = datetime.strptime("2019-07-12T05:49:55:2771249Z", "%Y-%m-%dT%H:%M:%S:%fZ")
print(utc_time1)

utc_time2 = datetime.strptime("2019-07-12T05:49:55.2771249Z", "%Y-%m-%dT%H:%M:%S.%fZ")
print(utc_time2)

I get the below error :

Traceback (most recent call last):
  File "C:/Users/bhatak/PycharmProjects/untitled/test.py", line 3, in <module>
    utc_time1 = datetime.strptime("2019-07-12T05:49:55:2771249Z", "%Y-%m-%dT%H:%M:%S:%fZ")
  File "C:\Users\bhatak\AppData\Local\Programs\Python\Python37-32\lib\_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\bhatak\AppData\Local\Programs\Python\Python37-32\lib\_strptime.py", line 359, in _strptime
    (data_string, format))
ValueError: time data '2019-07-12T05:49:55:2771249Z' does not match format '%Y-%m-%dT%H:%M:%S:%fZ'

Upvotes: 1

Views: 168

Answers (1)

Erdal Dogan
Erdal Dogan

Reputation: 617

From documentation, https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

When used with the strptime() method, the %f directive accepts from one to six digits and zero pads on the right. %f is an extension to the set of format characters in the C standard (but implemented separately in datetime objects, and therefore always available).

Your miliseconds have 7 digits, %f expression can have 6 at maximum. If you delete last one you will not have any problem.

277124 instead of 2771249.

Upvotes: 2

Related Questions