Question

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 ?

Was it helpful?

Solution

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")

OTHER TIPS

Use strptime from the time module

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top