Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading