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?

1
  • 3
    "Since it's a string, i cant do it with strftime()"... Sitting next to strftime is its opposite function strptime. Commented Sep 10, 2021 at 5:58

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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)
>>> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.