For starters, you have at least 4 bugs in your sample code:
- Your
strptime format requires a decimal point and digits after the seconds but your sample input doesn't have that.
- The
ts[:-7] bit doesn't slice the end off the string correctly. ts[:-6] would seem more correct: you want to slice 6 characters off the end of the string (2 for the tz hour, 2 for the tz minute, 1 for the :, and 1 for the + or -).
- You are adding the timezone offset where you should be subtracting it instead. You must subtract hours and minutes from a time given in an Eastern hemisphere timezone in order to get back to UTC, not add them.
- You are using
time.mktime() which assumes the timetuple is given in local time, but it's actually UTC. You need to use calendar.timegm() instead.
Here's your code updated to but the latter three problems. The first problem remains, because I did not know if you intended to force the presence of fractional seconds in the input string. You can adjust it further.
import datetime, time, calendar
def convert_enddate_to_seconds(ts):
"""Takes ISO 8601 format(string) and converts into epoch time."""
dt = datetime.datetime.strptime(ts[:-6],'%Y-%m-%dT%H:%M:%S.%f')-\
datetime.timedelta(hours=int(ts[-5:-3]),
minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
seconds = calendar.timegm(dt.timetuple()) + dt.microsecond/1000000.0
return seconds
Using 2010-01-04T12:15:30.1+01:00 as test input, I get 1262603730.1 as output, which is correct.
As for your question: no, you are not likely to be able to get much more concise than that if you just confine yourself to the standard library.
datetimemodule already comes with Python, you can simplyimportit without needing to download anything. It's difficult to use Python without being willing to use at least the builtin libraries.datetimeandtime; why isdateutilany different? Why not do all the math yourself, too?