Ivo
Ivo

Reputation: 4200

Convert to unix timestamp from "[YYYY]-[MM]-[DD]T[HH]:[MM]:[SS]+[XXXX]"

As part of a function, I get the input of date and time plus time zone in the format "[YYYY]-[MM]-[DD]T[HH]:[MM]:[SS]+[XXXX]" (with XXXX being the difference to UTC in HHMM) and need the date and time as a Unix time stamp.

I'm currently using time.mktime([CONVERTED TIME]) but end up with TypeError: function takes exactly 9 arguments (6 given). It seems like a lot of effort to program something for the arguments of 'weekday' etc. for time.mktime, so I'm sure there's a better way which I just didn't find yet.

How else can this be done?

Upvotes: 1

Views: 1562

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49794

This is a ISO 8601 compliant timestamp. There are various libraries which can help with these. But is your case, for a fixed format, you can use Python's dt.datetime.strptime and datetime.timedelta to calculate the seconds since epoch like:

Code:

def epoch_seconds_from_iso_8601_with_tz_offset(iso_8601):
    """ Convert ISO 8601 with a timezone offset to unix timestamp """
    iso_8601_dt = dt.datetime.strptime(iso_8601[:-5], '%Y-%m-%dT%H:%M:%S')
    utc_at_epoch = dt.datetime(1970, 1, 1)
    epoch_without_tz_offset = (iso_8601_dt - utc_at_epoch).total_seconds()
    tz_offset = 60 * (60 * int(iso_8601[-4:-2]) + int(iso_8601[-2:]))
    if iso_8601[-5] == '-':
        tz_offset = -tz_offset
    return epoch_without_tz_offset - tz_offset

Test Code:

import datetime as dt

t1 = epoch_seconds_from_iso_8601_with_tz_offset('2018-01-07T19:43:15+0000')
t2 = epoch_seconds_from_iso_8601_with_tz_offset('2018-01-07T11:43:15-0800')
epoch = 1515354195

assert epoch == t1 == t2

Upvotes: 1

Related Questions