Python difference between timezones - python

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:
have a non naive datetime
convert it

Related

Convert Local time to UTC before 1970

I'm trying to get UTC times for dates before 1970 but tz and tzinfo in Python only contain timezone databases for dates post-1970.
If I'm trying to find the UTC time for a date before 1970, say, Bill Clinton's birthday:
August 16, 1946 8:51AM
Hope, AK
datetime and tzinfo will return 16 Aug 1946 13:51 UTC
But it turns out that that is incorrect because it uses Chicago's timezone (which had its own timezone)
How can I find the proper time conversion and trust it for dates before 1970 in Python?
Time zone rules as we know them today came into play around 1900, see e.g. P. Eggert's tz repo. So Bill Clinton's birthday should not suffer from missing tz rules.
Ex, using pytz (deprecated):
from datetime import datetime
import pytz
bday = "August 16, 1946 8:51AM Hope, AK"
# Hope, AK is not a time zone, so strip it
bday = bday.rstrip(" Hope, AK")
# Hope in Arkansas uses US Central time, so we can use
tz = pytz.timezone("America/Chicago")
bday_dt = tz.localize(datetime.strptime(bday, "%B %d, %Y %I:%M%p"))
print(bday_dt)
# 1946-08-16 08:51:00-05:00
print(bday_dt.astimezone(pytz.UTC))
# 1946-08-16 13:51:00+00:00
...or using Python 3.9's zoneinfo
from zoneinfo import ZoneInfo
bday_dt = datetime.strptime(bday, "%B %d, %Y %I:%M%p").replace(tzinfo=ZoneInfo("America/Chicago"))
print(bday_dt)
# 1946-08-16 08:51:00-05:00
print(bday_dt.astimezone(ZoneInfo("UTC")))
# 1946-08-16 13:51:00+00:00

Converting UTC Time formatted string into Local Time Zone in Python [duplicate]

Is there an elegant way to display the current time in another time zone?
I would like to have something with the general spirit of:
cur = <Get the current time, perhaps datetime.datetime.now()>
print("Local time {}".format(cur))
print("Pacific time {}".format(<something like cur.tz('PST')>))
print("Israeli time {}".format(<something like cur.tz('IST')>))
A simpler method:
from datetime import datetime
from pytz import timezone
south_africa = timezone('Africa/Johannesburg')
sa_time = datetime.now(south_africa)
print sa_time.strftime('%Y-%m-%d_%H-%M-%S')
You could use the pytz library:
>>> from datetime import datetime
>>> import pytz
>>> utc = pytz.utc
>>> utc.zone
'UTC'
>>> eastern = pytz.timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
>>> amsterdam = pytz.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'
Python 3.9 (or higher): use zoneinfo from the standard lib:
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
# Israel and US/Pacific time:
now_Israel = datetime.now(ZoneInfo('Israel'))
now_Pacific = datetime.now(ZoneInfo('US/Pacific'))
print(f"Israeli time {now_Israel.isoformat(timespec='seconds')}")
print(f"Pacific time {now_Pacific.isoformat(timespec='seconds')}")
# Israeli time 2021-03-26T18:09:18+03:00
# Pacific time 2021-03-26T08:09:18-07:00
# for reference, local time and UTC:
now_local = datetime.now().astimezone()
now_UTC = datetime.now(tz=timezone.utc)
print(f"Local time {now_local.isoformat(timespec='seconds')}")
print(f"UTC {now_UTC.isoformat(timespec='seconds')}")
# Local time 2021-03-26T16:09:18+01:00 # I'm on Europe/Berlin
# UTC 2021-03-26T15:09:18+00:00
Note: there's a deprecation shim for pytz.
older versions of Python 3: you can either use zoneinfo via the backports module or use dateutil instead. dateutil's tz.gettz follows the same semantics as zoneinfo.ZoneInfo:
from dateutil.tz import gettz
now_Israel = datetime.now(gettz('Israel'))
now_Pacific = datetime.now(gettz('US/Pacific'))
print(f"Israeli time {now_Israel.isoformat(timespec='seconds')}")
print(f"Pacific time {now_Pacific.isoformat(timespec='seconds')}")
# Israeli time 2021-03-26T18:09:18+03:00
# Pacific time 2021-03-26T08:09:18-07:00
One way, through the timezone setting of the C library, is
>>> cur=time.time()
>>> os.environ["TZ"]="US/Pacific"
>>> time.tzset()
>>> time.strftime("%T %Z", time.localtime(cur))
'03:09:51 PDT'
>>> os.environ["TZ"]="GMT"
>>> time.strftime("%T %Z", time.localtime(cur))
'10:09:51 GMT'
The shortest ans of the question can be like:
from datetime import datetime
import pytz
print(datetime.now(pytz.timezone('Asia/Kolkata')))
This will print:
2019-06-20 12:48:56.862291+05:30
This script which makes use of the pytz and datetime modules is structured as requested:
#!/usr/bin/env python3
import pytz
from datetime import datetime, timezone
utc_dt = datetime.now(timezone.utc)
PST = pytz.timezone("US/Pacific")
IST = pytz.timezone("Asia/Jerusalem")
print("UTC time {}".format(utc_dt.isoformat()))
print("Local time {}".format(utc_dt.astimezone().isoformat()))
print("Pacific time {}".format(utc_dt.astimezone(PST).isoformat()))
print("Israeli time {}".format(utc_dt.astimezone(IST).isoformat()))
It outputs the following:
$ ./timezones.py
UTC time 2019-02-23T01:09:51.452247+00:00
Local time 2019-02-23T14:09:51.452247+13:00
Pacific time 2019-02-22T17:09:51.452247-08:00
Israeli time 2019-02-23T03:09:51.452247+02:00
This is my implementation:
from datetime import datetime
from pytz import timezone
def local_time(zone='Asia/Jerusalem'):
other_zone = timezone(zone)
other_zone_time = datetime.now(other_zone)
return other_zone_time.strftime('%T')
Can specify timezone by importing the modules datetime from datetime and pytx.
from datetime import datetime
import pytz
tz_NY = pytz.timezone('America/New_York')
datetime_NY = datetime.now(tz_NY)
print("NY time:", datetime_NY.strftime("%H:%M:%S"))
tz_London = pytz.timezone('Europe/London')
datetime_London = datetime.now(tz_London)
print("London time:", datetime_London.strftime("%H:%M:%S"))
tz_India = pytz.timezone('Asia/Kolkata')
datetime_India = datetime.now(tz_India)
print("India time:", datetime_India.strftime("%H:%M:%S"))
If you want a method which doesn't require importing pytz or any specific timezone libraries, you can do it in this way which only imports datetime. By using datetime to get the current UTC time then adding the timezone modifier, any desired timezone can be achieved.
For example, the timezone in New York is 4 hours behind UTC time, or UTC-04:00.
This means we can use this code to find the current time in New York:
import datetime
utc_time = datetime.datetime.utc(now)
tz_modifier = datetime.datetime.timedelta(hours=-4)
tz_time = utc_time + tz_modifier
print(tz_time)
To make this more "elegant" as was wanted, this method could be used:
from datetime import datetime, timedelta
utc = datetime.utcnow()
print("China time {}".format(utc+timedelta(hours=8)))
print("Greece time {}".format(utc+timedelta(hours=3)))
print("Hawaii time {}".format(utc+timedelta(hours=-10)))
The downside to this method is that the actual UTC differences of the timezones must be known already.
I need time info all time time, so I have this neat .py script on my server that lets me just select and deselect what time zones I want to display in order of east->west.
It prints like this:
Australia/Sydney : 2016-02-09 03:52:29 AEDT+1100
Asia/Singapore : 2016-02-09 00:52:29 SGT+0800
Asia/Hong_Kong : 2016-02-09 00:52:29 HKT+0800
EET : 2016-02-08 18:52:29 EET+0200
CET : 2016-02-08 17:52:29 CET+0100 <- you are HERE
UTC : 2016-02-08 16:52:29 UTC+0000
Europe/London : 2016-02-08 16:52:29 GMT+0000
America/New_York : 2016-02-08 11:52:29 EST-0500
America/Los_Angeles : 2016-02-08 08:52:29 PST-0800
Here source code is one .py file on my github here:
https://github.com/SpiRaiL/timezone
Or the direct file link:
https://raw.githubusercontent.com/SpiRaiL/timezone/master/timezone.py
In the file is a list like this:
Just put a 'p' in the places you want printed.
Put a 'h' for your own time zone if you want it specially marked.
(' ','America/Adak'), (' ','Africa/Abidjan'), (' ','Atlantic/Azores'), (' ','GB'),
(' ','America/Anchorage'), (' ','Africa/Accra'), (' ','Atlantic/Bermuda'), (' ','GB-Eire'),
(' ','America/Anguilla'), (' ','Africa/Addis_Ababa'), (' ','Atlantic/Canary'), (' ','GMT'),
(' ','America/Antigua'), (' ','Africa/Algiers'), (' ','Atlantic/Cape_Verde'), (' ','GMT+0'),
(' ','America/Araguaina'), (' ','Africa/Asmara'), (' ','Atlantic/Faeroe'), (' ','GMT-0'),
(' ','America/Argentina/Buenos_Aires'), (' ','Africa/Asmera'), (' ','Atlantic/Faroe'), (' ','GMT0'),
(' ','America/Argentina/Catamarca'), (' ','Africa/Bamako'), (' ','Atlantic/Jan_Mayen'), (' ','Greenwich'),
(' ','America/Argentina/ComodRivadavia'), (' ','Africa/Bangui'), (' ','Atlantic/Madeira'), (' ','HST'),
(' ','America/Argentina/Cordoba'), (' ','Africa/Banjul'), (' ','Atlantic/Reykjavik'), (' ','Hongkong'),
I end up using pandas a lot in my code, and don't like importing extra libraries if I don't have to, so here's a solution I'm using that's simple and clean:
import pandas as pd
t = pd.Timestamp.now('UTC') #pull UTC time
t_rounded = t.round('10min') #round to nearest 10 minutes
now_UTC_rounded = f"{t_rounded.hour:0>2d}{t_rounded.minute:0>2d}" #makes HH:MM format
t = pd.Timestamp.now(tz='US/Eastern') #pull Eastern (EDT or EST, as current) time
t_rounded = t.round('10min') #round to nearest 10 minutes
now_EAST_rounded = f"{t_rounded.hour:0>2d}{t_rounded.minute:0>2d}" #makes HH:MM format
print(f"The current UTC time is: {now_UTC_rounded} (rounded to the nearest 10 min)")
print(f"The current US/Eastern time is: {now_EAST_rounded} (rounded to the nearest 10 min)")
Outputs:
The current UTC time is: 1800 (rounded to the nearest 10 min)
The current US/Eastern time is: 1400 (rounded to the nearest 10 min)
(actual Eastern time was 14:03)
The rounding feature is nice because if you're trying to trigger something at a specific time, like on the hour, you can miss by 4 minutes on either side and still get a match.
Just showing off features - obviously you don't need to use the round if you don't want!
You can check this question.
Or try using pytz. Here you can find an installation guide with some usage examples.

Timedelta of datetime object and timezone object

I have a string datetime in YY/M/D/H which is already casted to PST timezone and saved. While reading it I am doing the following
submitted_time = '2020/02/13/11/16'
submitted_datetime = datetime.strptime(submitted_time, '%Y/%m/%d/%H/%M')
This time is already in PST timezone and to calculate the timedifference I tried doing the following :
from pytz import timezone
pacific = timezone('America/Los_Angeles')
today = datetime.now().astimezone(pacific)
But today - submitted_datetime won't work. I get the following error:
*** TypeError: can't subtract offset-naive and offset-aware datetimes
Is there a way I can get this working ? Any help is greatly appreciated.
With the code you provide, I doubt submitted_time will be interpreted as timezone aware, let alone PST. If you do convert it to a timezone aware datetime object, then the substraction works:
from datetime import datetime
from pytz import timezone
submitted_time = datetime.strptime('2020/02/13/11/16', '%Y/%m/%d/%H/%M')
pacific = timezone('America/Los_Angeles')
today = datetime.now().astimezone(pacific)
submitted_time = submitted_time.astimezone(pacific)
print(today - submitted_time)
Output:
5 days, 4:50:57.251801

Display the time in a different time zone

Is there an elegant way to display the current time in another time zone?
I would like to have something with the general spirit of:
cur = <Get the current time, perhaps datetime.datetime.now()>
print("Local time {}".format(cur))
print("Pacific time {}".format(<something like cur.tz('PST')>))
print("Israeli time {}".format(<something like cur.tz('IST')>))
A simpler method:
from datetime import datetime
from pytz import timezone
south_africa = timezone('Africa/Johannesburg')
sa_time = datetime.now(south_africa)
print sa_time.strftime('%Y-%m-%d_%H-%M-%S')
You could use the pytz library:
>>> from datetime import datetime
>>> import pytz
>>> utc = pytz.utc
>>> utc.zone
'UTC'
>>> eastern = pytz.timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
>>> amsterdam = pytz.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'
Python 3.9 (or higher): use zoneinfo from the standard lib:
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
# Israel and US/Pacific time:
now_Israel = datetime.now(ZoneInfo('Israel'))
now_Pacific = datetime.now(ZoneInfo('US/Pacific'))
print(f"Israeli time {now_Israel.isoformat(timespec='seconds')}")
print(f"Pacific time {now_Pacific.isoformat(timespec='seconds')}")
# Israeli time 2021-03-26T18:09:18+03:00
# Pacific time 2021-03-26T08:09:18-07:00
# for reference, local time and UTC:
now_local = datetime.now().astimezone()
now_UTC = datetime.now(tz=timezone.utc)
print(f"Local time {now_local.isoformat(timespec='seconds')}")
print(f"UTC {now_UTC.isoformat(timespec='seconds')}")
# Local time 2021-03-26T16:09:18+01:00 # I'm on Europe/Berlin
# UTC 2021-03-26T15:09:18+00:00
Note: there's a deprecation shim for pytz.
older versions of Python 3: you can either use zoneinfo via the backports module or use dateutil instead. dateutil's tz.gettz follows the same semantics as zoneinfo.ZoneInfo:
from dateutil.tz import gettz
now_Israel = datetime.now(gettz('Israel'))
now_Pacific = datetime.now(gettz('US/Pacific'))
print(f"Israeli time {now_Israel.isoformat(timespec='seconds')}")
print(f"Pacific time {now_Pacific.isoformat(timespec='seconds')}")
# Israeli time 2021-03-26T18:09:18+03:00
# Pacific time 2021-03-26T08:09:18-07:00
One way, through the timezone setting of the C library, is
>>> cur=time.time()
>>> os.environ["TZ"]="US/Pacific"
>>> time.tzset()
>>> time.strftime("%T %Z", time.localtime(cur))
'03:09:51 PDT'
>>> os.environ["TZ"]="GMT"
>>> time.strftime("%T %Z", time.localtime(cur))
'10:09:51 GMT'
The shortest ans of the question can be like:
from datetime import datetime
import pytz
print(datetime.now(pytz.timezone('Asia/Kolkata')))
This will print:
2019-06-20 12:48:56.862291+05:30
This script which makes use of the pytz and datetime modules is structured as requested:
#!/usr/bin/env python3
import pytz
from datetime import datetime, timezone
utc_dt = datetime.now(timezone.utc)
PST = pytz.timezone("US/Pacific")
IST = pytz.timezone("Asia/Jerusalem")
print("UTC time {}".format(utc_dt.isoformat()))
print("Local time {}".format(utc_dt.astimezone().isoformat()))
print("Pacific time {}".format(utc_dt.astimezone(PST).isoformat()))
print("Israeli time {}".format(utc_dt.astimezone(IST).isoformat()))
It outputs the following:
$ ./timezones.py
UTC time 2019-02-23T01:09:51.452247+00:00
Local time 2019-02-23T14:09:51.452247+13:00
Pacific time 2019-02-22T17:09:51.452247-08:00
Israeli time 2019-02-23T03:09:51.452247+02:00
This is my implementation:
from datetime import datetime
from pytz import timezone
def local_time(zone='Asia/Jerusalem'):
other_zone = timezone(zone)
other_zone_time = datetime.now(other_zone)
return other_zone_time.strftime('%T')
Can specify timezone by importing the modules datetime from datetime and pytx.
from datetime import datetime
import pytz
tz_NY = pytz.timezone('America/New_York')
datetime_NY = datetime.now(tz_NY)
print("NY time:", datetime_NY.strftime("%H:%M:%S"))
tz_London = pytz.timezone('Europe/London')
datetime_London = datetime.now(tz_London)
print("London time:", datetime_London.strftime("%H:%M:%S"))
tz_India = pytz.timezone('Asia/Kolkata')
datetime_India = datetime.now(tz_India)
print("India time:", datetime_India.strftime("%H:%M:%S"))
If you want a method which doesn't require importing pytz or any specific timezone libraries, you can do it in this way which only imports datetime. By using datetime to get the current UTC time then adding the timezone modifier, any desired timezone can be achieved.
For example, the timezone in New York is 4 hours behind UTC time, or UTC-04:00.
This means we can use this code to find the current time in New York:
import datetime
utc_time = datetime.datetime.utc(now)
tz_modifier = datetime.datetime.timedelta(hours=-4)
tz_time = utc_time + tz_modifier
print(tz_time)
To make this more "elegant" as was wanted, this method could be used:
from datetime import datetime, timedelta
utc = datetime.utcnow()
print("China time {}".format(utc+timedelta(hours=8)))
print("Greece time {}".format(utc+timedelta(hours=3)))
print("Hawaii time {}".format(utc+timedelta(hours=-10)))
The downside to this method is that the actual UTC differences of the timezones must be known already.
I need time info all time time, so I have this neat .py script on my server that lets me just select and deselect what time zones I want to display in order of east->west.
It prints like this:
Australia/Sydney : 2016-02-09 03:52:29 AEDT+1100
Asia/Singapore : 2016-02-09 00:52:29 SGT+0800
Asia/Hong_Kong : 2016-02-09 00:52:29 HKT+0800
EET : 2016-02-08 18:52:29 EET+0200
CET : 2016-02-08 17:52:29 CET+0100 <- you are HERE
UTC : 2016-02-08 16:52:29 UTC+0000
Europe/London : 2016-02-08 16:52:29 GMT+0000
America/New_York : 2016-02-08 11:52:29 EST-0500
America/Los_Angeles : 2016-02-08 08:52:29 PST-0800
Here source code is one .py file on my github here:
https://github.com/SpiRaiL/timezone
Or the direct file link:
https://raw.githubusercontent.com/SpiRaiL/timezone/master/timezone.py
In the file is a list like this:
Just put a 'p' in the places you want printed.
Put a 'h' for your own time zone if you want it specially marked.
(' ','America/Adak'), (' ','Africa/Abidjan'), (' ','Atlantic/Azores'), (' ','GB'),
(' ','America/Anchorage'), (' ','Africa/Accra'), (' ','Atlantic/Bermuda'), (' ','GB-Eire'),
(' ','America/Anguilla'), (' ','Africa/Addis_Ababa'), (' ','Atlantic/Canary'), (' ','GMT'),
(' ','America/Antigua'), (' ','Africa/Algiers'), (' ','Atlantic/Cape_Verde'), (' ','GMT+0'),
(' ','America/Araguaina'), (' ','Africa/Asmara'), (' ','Atlantic/Faeroe'), (' ','GMT-0'),
(' ','America/Argentina/Buenos_Aires'), (' ','Africa/Asmera'), (' ','Atlantic/Faroe'), (' ','GMT0'),
(' ','America/Argentina/Catamarca'), (' ','Africa/Bamako'), (' ','Atlantic/Jan_Mayen'), (' ','Greenwich'),
(' ','America/Argentina/ComodRivadavia'), (' ','Africa/Bangui'), (' ','Atlantic/Madeira'), (' ','HST'),
(' ','America/Argentina/Cordoba'), (' ','Africa/Banjul'), (' ','Atlantic/Reykjavik'), (' ','Hongkong'),
I end up using pandas a lot in my code, and don't like importing extra libraries if I don't have to, so here's a solution I'm using that's simple and clean:
import pandas as pd
t = pd.Timestamp.now('UTC') #pull UTC time
t_rounded = t.round('10min') #round to nearest 10 minutes
now_UTC_rounded = f"{t_rounded.hour:0>2d}{t_rounded.minute:0>2d}" #makes HH:MM format
t = pd.Timestamp.now(tz='US/Eastern') #pull Eastern (EDT or EST, as current) time
t_rounded = t.round('10min') #round to nearest 10 minutes
now_EAST_rounded = f"{t_rounded.hour:0>2d}{t_rounded.minute:0>2d}" #makes HH:MM format
print(f"The current UTC time is: {now_UTC_rounded} (rounded to the nearest 10 min)")
print(f"The current US/Eastern time is: {now_EAST_rounded} (rounded to the nearest 10 min)")
Outputs:
The current UTC time is: 1800 (rounded to the nearest 10 min)
The current US/Eastern time is: 1400 (rounded to the nearest 10 min)
(actual Eastern time was 14:03)
The rounding feature is nice because if you're trying to trigger something at a specific time, like on the hour, you can miss by 4 minutes on either side and still get a match.
Just showing off features - obviously you don't need to use the round if you don't want!
You can check this question.
Or try using pytz. Here you can find an installation guide with some usage examples.

Get time zone information of the system in Python?

I want to get the default timezone (PST) of my system from Python. What's the best way to do that? I'd like to avoid forking another process.
This should work:
import time
time.tzname
time.tzname returns a tuple of two strings: The first is the name of the local non-DST timezone, the second is the name of the local DST timezone.
Example return: ('MST', 'MDT')
Gives a UTC offset like in ThomasH's answer, but takes daylight savings into account.
>>> import time
>>> offset = time.timezone if (time.localtime().tm_isdst == 0) else time.altzone
>>> offset / 60 / 60 * -1
-9
The value of time.timezone or time.altzone is in seconds West of UTC (with areas East of UTC getting a negative value). This is the opposite to how we'd actually like it, hence the * -1.
time.localtime().tm_isdst will be zero if daylight savings is currently not in effect (although this may not be correct if an area has recently changed their daylight savings law).
EDIT: marr75 is correct, I've edited the answer accordingly.
I found this to work well:
import datetime
tz_string = datetime.datetime.now(datetime.timezone.utc).astimezone().tzname()
For me this was able to differentiate between daylight savings and not.
From Python 3.6 you can do:
tz_string = datetime.datetime.now().astimezone().tzname()
Or
tz_string = datetime.datetime.now().astimezone().tzinfo
Reference with more detail: https://stackoverflow.com/a/39079819/4549682
Check out the Python Time Module.
from time import gmtime, strftime
print(strftime("%z", gmtime()))
Pacific Standard Time
The code snippets for calculating offset are incorrect, see http://bugs.python.org/issue7229.
The correct way to handle this is:
def local_time_offset(t=None):
"""Return offset of local zone from GMT, either at present or at time t."""
# python2.3 localtime() can't take None
if t is None:
t = time.time()
if time.localtime(t).tm_isdst and time.daylight:
return -time.altzone
else:
return -time.timezone
This is in all likelihood, not the exact question that the OP asked, but there are two incorrect snippets on the page and time bugs suck to track down and fix.
For Python 3.6+ this can be easily achieved by following code:
import datetime
local_timezone = datetime.datetime.utcnow().astimezone().tzinfo
print(local_timezone)
But with Python < 3.6 calling astimezone() on naive datetime doesn't work. So we've to do it in a slightly different way.
So for Python 3.x,
import datetime
local_timezone = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo
print(local_timezone)
Sample Output:
On Netherlands Server(Python 3.6.9):
CEST
On Bangladesh Server(Python 3.8.2):
+06
More details can be found on this thread.
To obtain timezone information in the form of a datetime.tzinfo object, use dateutil.tz.tzlocal():
from dateutil import tz
myTimeZone = tz.tzlocal()
This object can be used in the tz parameter of datetime.datetime.now():
from datetime import datetime
from dateutil import tz
localisedDatetime = datetime.now(tz = tz.tzlocal())
or the tz parameter of datetime object via datetime.datetime.astimezone():
from datetime import datetime
from dateutil import tz
unlocalisedDatetime = datetime.now()
localisedDatetime = unlocalisedDatetime.astimezone(tz = tz.tzlocal())
Getting offset from UTC as timedelta:
from datetime import datetime, timezone
now = datetime.now()
now.replace(tzinfo=timezone.utc) - now.astimezone(timezone.utc)
Or like this (more obscure but also works):
datetime.now(timezone.utc).astimezone().tzinfo.utcoffset(None)
Both solutions give the same result. For example: datetime.timedelta(seconds=7200)
import tzlocal
tz_info = tzlocal.get_localzone() # 'US/Central' or 'Asia/Calcutta'
dt = datetime.now() # 2023-01-15 15:17:24.412430
print(tz_info.localize(dt) # 2023-01-15 15:17:24.412430-06:00
with tzlocal we will be able to get the local timezone.

Categories

Resources