0

I am trying to make some code that creates a clock using the user's local time with the datetime library.

import datetime as dt
import os
import time

z = dt.datetime.now()

def local_time():

    def time_check(t):
        if t < 10:
            t = "0{}".format(t)
        else:
            t = t
            
        return t

    p = dt.datetime.now()

    hour = p.hour
    minute = p.minute
    second = p.second 

    hour = time_check(hour)
    minute = time_check(minute)
    second = time_check(second)

    local_time = '{}:{}:{}'.format(hour, minute, second)
    return local_time

time_zone = z.timezone() 

for i in range(999999999999999999999):
    print("Time: {} {}".format(local_time(), time_zone))
    time.sleep(1)
    os.system("cls")

What I am doing is gathering the hour, minute, and second of the local time, and constantly updating it in the terminal, and deleting the previous time. This works fine, but I am also trying to display the timezone of the user, and I am having a hard time trying to find a way to do it. Does anyone know a way? Thanks.

NotASuperSpy
  • 43
  • 2
  • 6
  • e.g. [Get local time zone name on Windows](https://stackoverflow.com/q/62330675/10197418); and see also [Python: Figure out local timezone](https://stackoverflow.com/q/2720319/10197418). The easiest method is probably using `.astimezone(None)`, see [the docs](https://docs.python.org/3/library/datetime.html#datetime.datetime.astimezone). – FObersteiner May 24 '21 at 05:36

1 Answers1

0

Importing the python-dateutil library should make this easier. Install the library with the pip install python-dateutil command at the terminal if you don't have it installed beforehand. Once you do that, test the below code:

from datetime import *
from dateutil.tz import *

print(datetime.now(tzlocal()).tzname())
print(datetime(2021, 6, 2, 16, 00, tzinfo=tzlocal()).tzname())

#Output
#SA Western Standard Time
#SA Western Standard Time

Using tzlocal() and tzname() together will give you the current timezone. The dateutil library is very powerful and useful. Check out the full documentation HERE.

Hopefully that helped.