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.
CodePudding user response:
An alternative could be:
import datetime
import calendar
current_datetime = datetime.datetime.utcnow()
current_timetuple = current_datetime.utctimetuple()
current_timestamp = calendar.timegm(current_timetuple)
print(timestamp)
Output: 1633139754.681576
CodePudding user response:
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.