I want to find my local time zone and then return the time zone name (cet, est etc.) using Python and my location so that I can just find it without entering any additional information except for the location of my pc (which I want to find using GPS and not manually adding it)
import say
import datetime
def timezone():
timezone = datetime.datetime.now()
timezonename = timezone.strftime("%Z")
timezoneoffset = timezone.strftime("%z")
say.praten(f"the timezone is {timezonename} which is {timezoneoffset} off UTC")
I used this but this doesn't return anything with the datetime import the say command is from a different file for text to speech
everyone is revering me to this post : Get system local timezone in python but I tried this and I got the full name of the time zone (Europe Berlin) but I want the 3 letter name (cet in my case)
CodePudding user response:
You can use the time module to get your local timezone:
import time
print(time.tzname)
This gets you a tuple like ('CET', 'CEST')
.
CodePudding user response:
borrowing from this answer to the linked Q&A, you can also do
from datetime import datetime
dt_local = datetime.now().astimezone()
print(dt_local.isoformat(timespec="seconds"))
print(dt_local.strftime("%Z"))
# on my machine:
# 2022-11-09T18:50:13 01:00
# CET
The important part is to make the datetime object aware of the local time zone (setting of your machine) by calling .astimezone()
.