Like other questions asked here, im looking to do a simple conversion of time formats. I’ve found answers on how to do this in Perl, but not in Python.
I have a string like so:
on Jun 03, 02010 at 10:22PM
and I’d like to convert it to a datetime object like this:
Thu, 03 Jun 2010 22:22:00 -0000
I have sliced up my input like so:
date = str(comment.div.contents[5].contents)
month = date[6:9]
day = date[10:12]
year = date[15:19]
time = date[23:30]
which sets me up with some nice variables I can throw back into datetime but before I so, I must convert the time. Should I divide up time in the example above and calculate the hh and {AM|PM} separately?
Using dateutil:
If you can somehow strip out the pesky ‘on’ and change 02010 to 2010, in
date_strthen you could usedt.datetime.strptime:Or, as Muhammad Alkarouri points out, if
date_strs always start withonand use a four-digit year prefixed by zero, then you could usePython’s
strftimeandstrptimeuse your machine’s C functions of the same name. So check your local man page for what format codes are available for your machine. For a general list of format codes (which may be available) see https://www.php.net/strftime.