dorothy
dorothy

Reputation: 1243

How to find what time is it in another country from local

this time, i have questions on timezones in Python

How do i , say from anywhere in the world, convert that local time into say, New york time? first of, I think datetime module is the one to use. Should I use utcfromtimestamp() , then use some other functions to convert to New york time? How do i actually do that. thanks

Upvotes: 2

Views: 6565

Answers (2)

crjase
crjase

Reputation: 77

By local, I'm guessing you want it to be offline. You can use datetime and pytz package to convert the datetime into a time of any other country.

from tkinter import Tk, Button, Label, Entry, END
from datetime import datetime
import pytz

root = Tk()
root.title("Time In Arabia")


def center_window(w=400, h=200):
    ws = root.winfo_screenwidth()
    hs = root.winfo_screenheight()
    x = (ws/1.9) - (w/1.5)    
    y = (hs/3) - (h/2)
    root.geometry('%dx%d+%d+%d' % (w, h, x, y))

center_window(400, 200)

time = Entry(root)
time.pack()

def update():       #Put the timezone you want below
    timezone = pytz.timezone("Etc/GMT+3")
    local_time = datetime.now(timezone)
    current_time = local_time.strftime("%I:%M:%S%p")

    time.delete(0, END)
    time.insert(0, current_time)
    time.after(100, update)


root.after(100, update)
root.mainloop()

This should make an auto updating time thing. I set the time to Arabia (tried to atleast), you can just edit the time zone and make it into New York, or whatever you want. Have a look, see how it works.

Upvotes: 2

Patch Rick Walsh
Patch Rick Walsh

Reputation: 457

It sounds like you want to use the pytz module. The docs are very comprehensive and have some nice examples for you. http://pytz.sourceforge.net/

From the docs:

>>> from datetime import datetime, timedelta
>>> from pytz import timezone
>>> import pytz
>>> utc = pytz.utc
>>> utc.zone
'UTC'
>>> eastern = timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
>>> amsterdam = timezone('Europe/Amsterdam')
>>> fmt = '%Y-%m-%d %H:%M:%S %Z%z'
>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0))
>>> print(loc_dt.strftime(fmt))
2002-10-27 06:00:00 EST-0500
>>> ams_dt = loc_dt.astimezone(amsterdam)
>>> ams_dt.strftime(fmt)
'2002-10-27 12:00:00 CET+0100'

Upvotes: 7

Related Questions