Home > front end >  How to convert string in a datetime.datetime format into a datetime object?
How to convert string in a datetime.datetime format into a datetime object?

Time:09-17

I have a raw log which print timestamp in format of datetime.datetime(2021, 9, 10, 10, 15, 0, 250362). I believe some conversion has failed in the underlying program (out of my control).

Since it's a string, I can't do it with strftime().

Any way I could translate this into a datetime?

CodePudding user response:

datetime.strptime() can be used to validate a string and parse a date/time:

from datetime import datetime

s = 'datetime.datetime(2021, 9, 10, 10, 15, 0, 250362)'
dt = datetime.strptime(s,'datetime.datetime(%Y, %m, %d, %H, %M, %S, %f)')
print(dt)

Output:

2021-09-10 10:15:00.250362

CodePudding user response:

Try with this:

>>> s = 'datetime.datetime(2021, 9, 10, 10, 15, 0, 250362)'
>>> datetime.datetime(*map(int, s[s.find('(')   1: -1].split(', ')))
datetime.datetime(2021, 9, 10, 10, 15, 0, 250362)
>>> 
  • Related