Reputation: 4251
I have a time format like this
t = "2012-03-20T08:31:00-05:00"
I can extract the time contents using RegEx like this.
p = re.compile("(\d{4})\-(\d\d)\-(\d\d)T(\d\d):(\d\d):(\d\d)[\-|+]\d\d:\d\d")
matches = p.findall(t)
But I was wondering if there is a way to convert this format directly to unix_timestamp without using RegEx ? Is there a calendar library or something similar ?
Upvotes: 2
Views: 283
Reputation: 157414
Use time.strptime
:
time.strptime(t, "%Y-%m-%dT%H:%M:%S-%Z")
Unfortunately, this doesn't appear to work with numeric time zone offsets. python-dateutil should be able to handle your format:
dateutil.parser.parse(t)
Alternatively, you could split your string before the numeric offset:
t, offset_sign, offset = t[:-6], t[-6], t[-5:]
t = time.strptime(t, "%Y-%m-%dT%H:%M:%S")
offset = time.strptime(offset, "%H:%M")
Upvotes: 1
Reputation: 91
datetime.datetime.strptime
is your friend :)
http://docs.python.org/library/datetime.html#datetime.datetime.strptime
Upvotes: 2