0

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
hellojoshhhy
  • 855
  • 2
  • 15
  • 32
  • 3
    "Since it's a string, i cant do it with strftime()"... Sitting next to `strftime` is its opposite function [`strptime`](https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime). – blhsing Sep 10 '21 at 05:58

2 Answers2

3

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
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
1

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)
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114