Home > Back-end >  Converting a given string to datetime
Converting a given string to datetime

Time:06-28

I'm trying to convert a string '2022-06-27 17:00:1656349200' to datetime, using

t = '2022-06-27 17:00:1656349200'
t__ = time.strptime(t, "%Y-%m-%dT%H:%M:%S")
ts = datetime.datetime.fromtimestamp(time.mktime(t__))
dt = ts.replace(microsecond=int(frag))
print(dt)

But getting an error : ValueError: unconverted data remains: 56349200

CodePudding user response:

You need to fix the .strptime() parsing string parameter as follows:

import time
import datetime

t = '2022-06-27 17:00:1656349200'[:-2]
t__ = time.strptime(t, "%Y-%m-%d %H:%M:%S%f")
ts = datetime.datetime.fromtimestamp(time.mktime(t__))
dt = ts.replace(microsecond=int(frag))
print(dt)

CodePudding user response:

That date string looks a bit off. Normally you'd separate the milliseconds from the seconds with a dot: 2022-06-27 17:00:16.563. Dot or not, you can read milliseconds with %f. So this gets you close:

datetime.strptime(t, "%Y-%m-%d %H:%M:%S%f")

Unfortunately this will still complain about the last two digits:

>>> datetime.strptime("2022-06-27 17:00:1656349200", "%Y-%m-%d %H:%M:%S%f")
...
ValueError: unconverted data remains: 00

So the %f can read the milliseconds and the microseconds, but the last two digits are too much. So the question becomes: Do you really need nanosecond precision? What are these zeroes doing there? Python's datetime cannot represent nanoseconds, so you'd have to use another data structure to store them.

If you don't need that much precision, and the date strings you are reading are always the same format, just cut them off:

datetime.strptime(t[:25], "%Y-%m-%d %H:%M:%S%f")

It could also be that the last two digits are something else, like a timezone. But when things are mashed together like that, it is not clear what they are supposed to represent. So my recommendation ist o ignore everything after the seconds, unless you know what it is:

datetime.strptime(t[:19], "%Y-%m-%d %H:%M:%S")
  • Related