1

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)

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Tijmi
  • 45
  • 8
  • 1
    Does this answer your question? [Get system local timezone in python](https://stackoverflow.com/questions/35057968/get-system-local-timezone-in-python) – Woodford Nov 09 '22 at 16:52
  • Note that abbreviated time zone names such as CET or EST are ambiguous. Use IANA time zone names instead to avoid the ambiguity. – FObersteiner Nov 09 '22 at 17:22

2 Answers2

2

You can use the time module to get your local timezone:

import time
print(time.tzname)

This gets you a tuple like ('CET', 'CEST').

Kaitonee
  • 33
  • 5
0

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().

FObersteiner
  • 22,500
  • 8
  • 42
  • 72