I have a list of datetimes that were imported as strings:
datetimes = ['datetime.datetime(2021, 2, 16, 12, 39, 54, 30886)', 'datetime.datetime(2021, 2, 16, 12, 40, 5, 238783)' ... ]
How can I convert the string into a datetime object?
I have a list of datetimes that were imported as strings:
datetimes = ['datetime.datetime(2021, 2, 16, 12, 39, 54, 30886)', 'datetime.datetime(2021, 2, 16, 12, 40, 5, 238783)' ... ]
How can I convert the string into a datetime object?
there are many ways to do this, here is one
import datetime
def todate(s):
prefix = 'datetime.datetime('
parts = [int(x) for x in s[len(prefix):-1].split(", ")]
return datetime.datetime(*parts)
datetimes = ['datetime.datetime(2021, 2, 16, 12, 39, 54, 30886)', 'datetime.datetime(2021, 2, 16, 12, 40, 5, 238783)']
print([todate(x) for x in datetimes])
This is python source code cast as a string. Rather than write a custom parser, you're far better off parsing it with... python's parser :). This can be achieved with eval
:
import datetime
dt_vec = [eval(dt) for dt in datetimes]
output:
[datetime.datetime(2021, 2, 16, 12, 39, 54, 30886),
datetime.datetime(2021, 2, 16, 12, 40, 5, 238783)]
This comes with a strong caveat: dont use eval if you don't know where the code came from, or can see that it is malicious. In truth, you run code on your computer all the time that you don't inspect (every download a binary and run it?) but worth being mindful of.