Parsing datetime string containing milliseconds to datetime

Viewed 204

I have some datetime strings containing miliseconds from midnight. How do I parse these to yyyy-MM-dd HH:mm:ss, for instance 2020-04-07 08:30:35 using Python?

2020-04-01#21120000
2020-04-06#60300000
2020-04-07#55620000
2020-04-08#56820000
2020-04-09#57240000
2020-04-10#56580000
2020-04-14#27720000
2020-04-15#20880000
2020-04-16#21300000
2020-04-17#21000000
2020-04-20#21060000
2020-04-21#20940000
1 Answers

Some manual splitting and parsing, adding the millisecond part to the midnight point of the date using timedelta:

from datetime import datetime, timedelta

ts = '2020-04-01#21120000'
d, ms = ts.split('#')
dt = datetime.strptime(d, '%Y-%m-%d') + timedelta(milliseconds=int(ms))
# datetime.datetime(2020, 4, 1, 5, 52)
Related