Search code examples
pythondatetimetimezoneutc

datetime.utcfromtimestamp changing time in python


I have a string representing a datetime (ts). I want to transform it to int and then use datetime.utcfromtimestamp to recover the same datetime:

ts = '2023-07-10 14:06:22.000 UTC'
int_ts = int(datetime.strptime(ts, "%Y-%m-%d %H:%M:%S.%f %Z").timestamp() * 1000) # change this line, cannot change the previous or next
back_to_ts = datetime.utcfromtimestamp(int_ts / 1000)
print(f"{back_to_ts = }, {ts = }, {int_ts = }")

However, I get the following output:

back_to_ts = datetime.datetime(2023, 7, 10, 12, 6, 22), ts = '2023-07-10 14:06:22.000 UTC', int_ts = 1688990782000

I can only change the second line, how should I change it to get the follwoing output?

back_to_ts = datetime.datetime(2023, 7, 10, 14, 6, 22), ts = '2023-07-10 14:06:22.000 UTC', int_ts = 1688990782000

Solution

  • You need to replace the timezone in your datetime object before the converting it to a timestamp. See the .replace(tzinfo=timezone.utc) part of the second line.

    ts = '2023-07-10 14:06:22.000 UTC'
    int_ts = int(datetime.strptime(ts, "%Y-%m-%d %H:%M:%S.%f %Z").replace(tzinfo=timezone.utc).timestamp() * 1000)
    back_to_ts = datetime.utcfromtimestamp(int_ts / 1000)
    

    Output:

    back_to_ts = datetime.datetime(2023, 7, 10, 14, 6, 22), ts = '2023-07-10 14:06:22.000 UTC', int_ts = 1688997982000