0

In my program, I need to use a datetime object that is in utc time not my local time, and I also need the timestamp (seconds since epoch) of that datetime object.

import datetime

my_time = datetime.datetime.utcnow()
timestamp = my_time.timestamp()

However, the timestamp was wrong. It was the timestamp when my local time is my_time, not the correct timestamp when the utc time is my_time. How can I get the correct timestamp? I don't want to create another datetime object because there might be microseconds of difference.

Edit

Example:

import datetime

utc_time = datetime.datetime.utcnow()
local_time = datetime.datetime.now()

utc_timestamp = utc_time.timestamp()
local_timestamp = local_time.timestamp()

print(utc_timestamp)
print(local_timestamp)

My result:

1633133103.945903
1633161903.945903

The two are different by 8 hours, because I live in UTC+08:00 time zone, and the first one is not "seconds since epoch". I want to get the correct timestamp from utc_time because technically those two object were not created at the same time.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Jeffrey Chen
  • 1,777
  • 1
  • 18
  • 29
  • please add your expected output – Sabil Oct 02 '21 at 07:52
  • What is your time zone, and the discrepancy from UTC? Do other time-related utilities on your system report UTC time correctly? – tripleee Oct 02 '21 at 08:00
  • the problem here is that `datetime.datetime.utcnow()` gives a naive datetime object, that has attributes set to current UTC time - however, since the ***object is naive***, Python will treat it like ***local time*** - which is why `.timestamp()` returns an unexpected result. I therefore suggest to avoid `utcnow()` altogether. – FObersteiner Oct 02 '21 at 09:17

1 Answers1

1

use aware datetime,

from datetime import datetime, timezone

t_loc = datetime.now().astimezone() # local time, as set in my OS (tz Europe/Berlin)
t_utc = datetime.now(timezone.utc)

print(repr(t_loc))
print(repr(t_utc))
# e.g.
# datetime.datetime(2021, 10, 2, 11, 10, 26, 920792, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), 'CEST'))
# datetime.datetime(2021, 10, 2, 9, 10, 26, 920809, tzinfo=datetime.timezone.utc)

This will give you correct Unix time as well:

t_loc_unix = t_loc.timestamp()
t_utc_unix = t_utc.timestamp()

print(t_loc_unix, t_utc_unix)
# 1633165826.920792 1633165826.920809

Unix timestamps are now equal as it should be since Unix time always (should) refers to UTC.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72