Search code examples
pythondatetimetimezoneepoch

Converting string date to utc epoch in Python


I have a UTC time as string, I want to convert it to UTC timestamp. But following code seems to again convert it to UTC causing it to be wrong timestap. How do I convert that datetime format to timestamp so that it preserves it as UTC.

datetime.strptime('2023-08-02 14:52:05', '%Y-%m-%d %H:%M:%S').timestamp() * 1000

Input time GMT: 2023-08-02 14:52:05  
Outputs GMT: 1691002325000.0     
# This converts to GMT: Wednesday, August 2, 2023 6:52:05 PM https://www.epochconverter.com/

Solution

  • TL;DR: Use

    datetime.fromisoformat(f"{utc_time_string}+00:00").timestamp() * 1000
    

    Your observation about the error is correct. And that's because:

    Naive datetime instances are assumed to represent local time and this method relies on the platform C mktime() function to perform the conversion.

    The docs also show how to get the timestamp from a naive datetime object which represents UTC:

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

    So you could do it as:

    (
        datetime
            .strptime('2023-08-02 14:52:05', '%Y-%m-%d %H:%M:%S')
            .replace(tzinfo=timezone.utc)
            .timestamp() * 1000
    )
    

    Outputs 1690987925000.0 which is GMT: Wednesday, August 2, 2023 2:52:05 PM

    Since you appear to have an almost-ISO datetime string, you could also use .fromisoformat() and affix add "+00:00" at the end of the string before the conversion. That generates a TZ-aware datetime object and .timestamp() handles that properly:

    utc_time_string = '2023-08-02 14:52:05'
    (
        datetime
            .fromisoformat(f"{utc_time_string}+00:00")
            .timestamp() * 1000
    )
    # fits nicely on one line
    datetime.fromisoformat(f"{utc_time_string}+00:00").timestamp() * 1000
    

    Also outputs 1690987925000.0.

    For Python 3.11 onwards, you can add the suffix "Z" instead of "+00:00".