Search code examples
pythontimetimezoneunix-timestamputc

Parse Date String to UTC UNIX Format


I have a timestamp in string format

timestamp_str = '18:02:19 14:14:11 465872'
format_str = '%y:%m:%d %H:%M:%S %f'

and to convert it to UTC in UNIX I have written the following code

def str2utc(timestr,formatstr):
    timeobj = datetime.datetime.strptime(timestr, formatstr)
    time_utc = time.mktime(timeobj.timetuple())
    return time_utc

timestamp_utc_unix = str2utc(timestamp_str,format_str)

Nevertheless, as I already know, this does not work if my system time is something else than utc. I have read other posts like

Python strptime() and timezones?

but just cannot wrap my head around how to correct it. How do I have to change the code so that not matter what my system time is it always outputs utc in unix?


Solution

  • Python docs:

    Note

    There is no method to obtain the POSIX timestamp directly from a naive datetime instance representing UTC time. If your application uses this convention and your system timezone is not set to UTC, you can obtain the POSIX timestamp by supplying tzinfo=timezone.utc:

    timestamp = dt.replace(tzinfo=timezone.utc).timestamp()

    or by calculating the timestamp directly:

    timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

    So your function would look like

    def str2utc(timestr,formatstr):
        timeobj = datetime.datetime.strptime(timestr, formatstr)
        time_utc = timeobj.replace(tzinfo=datetime.timezon.utc).timestamp()
        return time_utc
    

    I'm getting a value of 1519049651.465872, which matches what I get from unixtimestamp.com