I'm getting a datetime string in a format like "2009-05-28T16:15:00" (this is ISO 8601, I believe). One hackish option seems to be to parse the string using
time.strptime and passing the first six elements of the tuple into the datetime constructor, like:
I haven't been able to find a "cleaner" way of doing this. Is there one?
I prefer using the dateutil library for timezone handling and generally solid date parsing. If you were to get an ISO 8601 string like: 2010-05-08T23:41:54.000Z you'd have a fun time parsing that with strptime, especially if you didn't know up front whether or not the timezone was included. pyiso8601 has a couple of issues (check their tracker) that I ran into during my usage and it hasn't been updated in a few years. dateutil, by contrast, has been active and worked for me:
import dateutil.parser yourdate = dateutil.parser.parse(datestring)
Since Python 3.7 and no external libraries:
Python 2 doesn't support the
%z format specifier, so it's best to explicitly use Zulu time everywhere if possible: