FpRoT
FpRoT

Reputation: 63

Python difference between timezones

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

Upvotes: 1

Views: 1843

Answers (1)

Jonathan Adami
Jonathan Adami

Reputation: 356

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:

  • have a non naive datetime
  • convert it

Upvotes: 1

Related Questions