-1

I have a string in this format: 2019-06-18T11:00:10.499378622Z. I am trying to convert this into a datetime object.

I have tried

s_datetime = datetime.strptime(s_datetime_string, '%Y-%m-%d*%H:%M:%S*')
import datetime.datetime
s_datetime = datetime.strptime(s_datetime_string, '%Y-%m-%d*%H:%M:%S*')

Getting ValueError as the regex does not match
DevBabai
  • 83
  • 12

2 Answers2

1

I also get this error, so I made a little function to use whenever I deal with ISO times.

def ISOtstr(iso):

    dcomponents = [1,1,1]
    dcomponents[0] = iso[:4]
    dcomponents[1] = iso[5:7]
    dcomponents[2] = iso[8:10]
    tcomponents = [1,1,1]
    tcomponents[0] = iso[11:13]
    tcomponents[1] = iso[14:16]
    tcomponents[2] = iso[17:19]
    d = dcomponents
    t = tcomponents
    string = "{}-{}-{} {}:{}:{}".format(d[0],d[1],d[2],t[0],t[1],t[2])
    return string

Convert your ISO to a string:

string = '2019-06-18T11:00:10.499378622Z'
date_string = ISOtstring(string)
date_obj = datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
#Output
#datetime.datetime(2019, 6, 18, 11, 0, 10)

There is most likely a better way to do it. But I use this whenever dealing with ISO strings.

If your using it frequently you could make this a separate function:

def ISOtdatetime(iso):
  date_string = ISOtstring(iso)
  date_obj = datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
  return date_obj

Just realized I had some meaningless code in there from when I first created the function. They have been removed.

Robert Kearns
  • 1,631
  • 1
  • 8
  • 15
0

I also got an error with your input especially on the unit of second. But when I changed your unit of second a little bit, it works. So, I have no idea about this.

from datetime import datetime

s_datetime = datetime.strptime('2019-06-18T11:00:10.499378Z', '%Y-%m-%dT%H:%M:%S.%fZ')
print(s_datetime)
print(type(s_datetime))

Output:

2019-06-18 11:00:10.499378
<class 'datetime.datetime'>
YusufUMS
  • 1,506
  • 1
  • 12
  • 24
  • I am still having trouble with it :/ `ValueError: time data '2019-06-18T15:08:46.131737185Z' does not match format '%Y-%m-%dT%H:%M:%S.%fZ' – DevBabai Jun 19 '19 at 03:04