2

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
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Luukv93
  • 339
  • 1
  • 6
  • 19

1 Answers1

2

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)
deceze
  • 510,633
  • 85
  • 743
  • 889
  • 1
    `datetime.fromisoformat(d)` also works here and seems to be [more efficient](https://stackoverflow.com/a/61710371/10197418) - in case the OP needs to do the a lot of times. – FObersteiner May 11 '20 at 14:22