0

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?

Po Chen Liu
  • 253
  • 2
  • 12
  • 2
    This is well-answered elsewhere on SA: [https://stackoverflow.com/questions/466345/converting-string-into-datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) – Tom Darby Feb 16 '21 at 03:02
  • 1
    My apologies, I didn't realise I could also include words not related to the datetime object, cheers! – Po Chen Liu Feb 16 '21 at 03:16
  • 1
    @TomDarby this is not parsing standard formatted date, this is python code for constructing date time objects. – anon01 Feb 16 '21 at 03:27

2 Answers2

0

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])
D. Seah
  • 4,472
  • 1
  • 12
  • 20
0

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.

anon01
  • 10,618
  • 8
  • 35
  • 58