I have to create a code that can tell me the current time in any city (as a variable) and print the utc offset between that time and utc. I already have the following code which gives the current time and the offset from a timezone, but this timezone is not always utc. Note: the city names are stored in a text file and the user should be able to add and remove any city. I am using tkinter for the gui.
from datetime import datetime, timedelta
from pytz import timezone
import pytz
def tz():
utc = pytz.utc
amsterdam = timezone('Europe/Amsterdam')
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
loc_dt = utc.localize(datetime.today())
tz = loc_dt.astimezone(amsterdam)
print(tz.strftime(fmt))
The file contents are as follows:
Amsterdam
Brasilia
Los Angeles
Abu Dhabi
Tokyo
Singapore
Can someone please help me with an easy code to do this? Thank you in advance
You're using pytz already, so I'd go for:
from datetime import datetime
from pytz import timezone, all_timezones
def to_timezone(dt, tz):
assert dt.tzinfo is not None
assert tz in all_timezones
return dt.astimezone(timezone(tz))
print to_timezone(datetime.now(timezone('UTC')), 'Europe/Amsterdam')
I set it to UTC by default but the point is:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.