'Get GMT timestamp in python
I need to get GMT timestamps, a timestamp when start a day, and another when end a day, the following example is for today (2022-03-29):
Start of Day (Unix Timestamp): 1648512000
End of Day (Unix Timestamp): 1648598399
you can check this in https://www.epochconvert.com/
and my code only for the case of start of day is the next one :
from datetime import datetime
start_date = datetime.today().strftime('%Y-%m-%d')
start_date += ' 00:00:00'
print(start_date)
timestamp = time.mktime(datetime.strptime(start_date, "%Y-%m-%d %H:%M:%S").timetuple())
print(timestamp)
and my output:
2022-03-29 00:00:00
1648533600.0
as you can see it's not the answer I'm waiting for, that timestamp is for my Local Time but i need a GMT timestamp as answer (1648512000 in this case)
How could i do it ? Thanks in Advance!!
Solution 1:[1]
if you want to derive Unix time from datetime objects, make sure to set time zone / have aware datetime:
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
print(now)
# 2022-03-29 23:34:51.701712+00:00
now_floored = datetime.combine(now.date(), now.time().min).replace(tzinfo=timezone.utc)
print(now_floored)
# 2022-03-29 00:00:00+00:00
now_floored_unix = now_floored.timestamp()
print(now_floored_unix)
# 1648512000.0
If you do not do that (have naive datetime), Python will use local time:
now = datetime.now()
now_floored = datetime.combine(now.date(), now.time().min)
print(now_floored.astimezone())
# 2022-03-29 00:00:00-06:00 # <- my current UTC offset is -6 hours
print(now_floored.timestamp(), (now_floored_unix-now_floored.timestamp())//3600)
# 1648533600.0 -6.0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |