In Python, how do you find what UTC time offset the computer is set to?
9 Answers
import time
print -time.timezone
It prints UTC offset in seconds (to take into account Daylight Saving Time (DST) see time.altzone:
is_dst = time.daylight and time.localtime().tm_isdst > 0
utc_offset = - (time.altzone if is_dst else time.timezone)
where utc offset is defined via: "To get local time, add utc offset to utc time."
In Python 3.3+ there is tm_gmtoff
attribute if underlying C library supports it:
utc_offset = time.localtime().tm_gmtoff
Note: time.daylight
may give a wrong result in some edge cases.
tm_gmtoff
is used automatically by datetime if it is available on Python 3.3+:
from datetime import datetime, timedelta, timezone
d = datetime.now(timezone.utc).astimezone()
utc_offset = d.utcoffset() // timedelta(seconds=1)
To get the current UTC offset in a way that workarounds the time.daylight
issue and that works even if tm_gmtoff
is not available, @jts's suggestion to substruct the local and UTC time can be used:
import time
from datetime import datetime
ts = time.time()
utc_offset = (datetime.fromtimestamp(ts) -
datetime.utcfromtimestamp(ts)).total_seconds()
To get UTC offset for past/future dates, pytz
timezones could be used:
from datetime import datetime
from tzlocal import get_localzone # $ pip install tzlocal
tz = get_localzone() # local timezone
d = datetime.now(tz) # or some other local date
utc_offset = d.utcoffset().total_seconds()
It works during DST transitions, it works for past/future dates even if the local timezone had different UTC offset at the time e.g., Europe/Moscow timezone in 2010-2015 period.
-
3This is nice and clean. – Rockallite Dec 19 '13 at 02:25
-
Note that `total_seconds()` is available only in Python 3.2+. – mattst Jun 04 '16 at 13:46
-
1@mattst `total_seconds()` is available in Python 2.7 and [it is easy to emulate it on earlier Python versions](http://stackoverflow.com/a/8778548) – jfs Jun 04 '16 at 13:54
-
@JFSebastian Ok and thanks, I checked and you are right. Please note that the [Python 3.3 docs](https://docs.python.org/3.3/library/datetime.html?#datetime.timedelta.total_seconds) say `total_seconds()` was introduced in 3.2. – mattst Jun 04 '16 at 14:07
-
Can't believe Python does not come with `utc2local(...)` and `local2utc(...)`. Glad that @jfs comes to rescue! Upvoted! – RayLuo Feb 24 '19 at 10:10
-
1@RayLuo it depends on what you mean exactly. Here's an [implementation for utc2local](https://stackoverflow.com/q/4563272/4279) – jfs Feb 24 '19 at 15:00
-
In your first example, why is it necessary to check for DST twice? Shouldn't it be enough to use the output of `time.timezone`? – charliesneath Jun 07 '20 at 19:03
-
@charliesneath: do you mean the second example (with `is_dst`) and `time.daylight`? https://docs.python.org/3/library/time.html#timezone-constants – jfs Jun 08 '20 at 18:32
-
`datetime.datetime.utcfromtimestamp` is deprecated in Python 3.12. I think the replacement is to do: `local_time = datetime.datetime.fromtimestamp(timestamp); utc_time = datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc); tzdelta = local_time - utc_time.replace(tzinfo=None)` (then call `.total_seconds()` on `tzdelta` if that's what you need). – Henry Schreiner Jun 20 '23 at 22:11
-
@HenrySchreiner it is not applicable here: if you have access to the timezone-aware datetime object that represents local time, then just call its `utcoffset()` method to get the utc offset (like the `get_localzone()` case in the answer but `zoneinfo` is available in stdlib now. – jfs Jun 23 '23 at 03:29
gmtime()
will return the UTC time and localtime()
will return the local time so subtracting the two should give you the utc offset.
From https://pubs.opengroup.org/onlinepubs/009695399/functions/gmtime.html
The gmtime() function shall convert the time in seconds since the Epoch pointed to by timer into a broken-down time, expressed as Coordinated Universal Time (UTC).
So, despite the name gmttime
, the function returns UTC.
-
4Subtracting them gives `TypeError: unsupported operand type(s) for -: 'time.struct_time' and 'time.struct_time'`. What did you really mean? – rakslice May 01 '15 at 21:45
-
5rakslice, try calendar.timegm(time.gmtime()) - calendar.timegm(time.localtime())) – Casey Perkins Jun 22 '15 at 22:06
-
8@JasonTyler: to avoid races: [`t = localtime(); timegm(t) - timegm(gmtime(mktime(t)))`](https://mail.python.org/pipermail/datetime-sig/2015-September/000955.html) – jfs Sep 29 '15 at 09:44
-
1@Kirby: [`gmtime()` returns UTC *always*](https://pubs.opengroup.org/onlinepubs/009695399/functions/gmtime.html). There are cases when GMT!=UTC but it is not it. – jfs Mar 15 '20 at 08:09
-
-
I edited the question to add your clarification which also then enables me to convert my downvote to an upvote ;) – Kirby Mar 24 '20 at 17:42
-
1@Kirby - GMT is a time zone and UTC is a time standard. Also, neither UTC nor GMT ever change for Daylight Saving Time (DST). (However, some of the countries that use GMT switch to different time zones during their DST period) – EvgenyKolyakov Oct 04 '20 at 08:28
I like:
>>> strftime('%z')
'-0700'
I tried JTS' answer first, but it gave me the wrong result. I'm in -0700 now, but it was saying I was in -0800. But I had to do some conversion before I could get something I could subtract, so maybe the answer was more incomplete than incorrect.

- 6,954
- 1
- 26
- 27
-
2`'%z'` is not supported by Python (it may work on some systems where you likely could use `time.localtime().tm_gmtoff` instead, to get the utc offset as a number, not string). The result (of `'%z'`) should be identical with @jts' answer. Include your code if you think otherwise. – jfs Apr 04 '15 at 13:23
-
import time time0 = time.time() utc_time = time.mktime(time.gmtime(time0)) local_time = time.mktime(time.localtime(time0)) offset = local_time - utc_time print(offset / (60 * 60)) Gives -8. – dstromberg Apr 04 '15 at 18:09
-
11. don't put the code in the comments, update your answer instead 2. it is incorrect to use mktime() here, use `calendar.timegm()` or `datetime()` to find the difference – jfs Apr 04 '15 at 18:24
-
2@dstromberg I think this is the best approach) I like it! My solution was: `int(datetime.now().astimezone().strftime("%z")[0:3])` – storenth Oct 31 '22 at 09:39
the time module has a timezone offset, given as an integer in "seconds west of UTC"
import time
time.timezone

- 339
- 2
- 7
You can use the datetime
and dateutil
libraries to get the offset as a timedelta
object:
>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>>
>>> # From a datetime object
>>> current_time = datetime.now(tzlocal())
>>> current_time.utcoffset()
datetime.timedelta(seconds=7200)
>>> current_time.dst()
datetime.timedelta(seconds=3600)
>>>
>>> # From a tzlocal object
>>> time_zone = tzlocal()
>>> time_zone.utcoffset(datetime.now())
datetime.timedelta(seconds=7200)
>>> time_zone.dst(datetime.now())
datetime.timedelta(seconds=3600)
>>>
>>> print('Your UTC offset is {:+g}'.format(current_time.utcoffset().total_seconds()/3600))
Your UTC offset is +2

- 3,624
- 8
- 42
- 57
hours_delta = (time.mktime(time.localtime()) - time.mktime(time.gmtime())) / 60 / 60

- 636
- 1
- 8
- 14
-
-
1Actually GMT is the same as UTC. In the UK we have British Summer Time (BST) for daylight savings. See, for example, https://greenwichmeantime.com/what-is-gmt/ where it says "GMT (Daylight Saving Time never applies)". – IpsRich Dec 05 '19 at 14:30
Create a Unix Timestamp with UTC Corrected Timezone
This simple function will make it easy for you to get the current time from a MySQL/PostgreSQL database date
object.
def timestamp(date='2018-05-01'):
return int(time.mktime(
datetime.datetime.strptime( date, "%Y-%m-%d" ).timetuple()
)) + int(time.strftime('%z')) * 6 * 6
Example Output
>>> timestamp('2018-05-01')
1525132800
>>> timestamp('2018-06-01')
1527811200

- 6,498
- 2
- 34
- 46
Here is some python3 code with just datetime and time as imports. HTH
>>> from datetime import datetime
>>> import time
>>> def date2iso(thedate):
... strdate = thedate.strftime("%Y-%m-%dT%H:%M:%S")
... minute = (time.localtime().tm_gmtoff / 60) % 60
... hour = ((time.localtime().tm_gmtoff / 60) - minute) / 60
... utcoffset = "%.2d%.2d" %(hour, minute)
... if utcoffset[0] != '-':
... utcoffset = '+' + utcoffset
... return strdate + utcoffset
...
>>> date2iso(datetime.fromtimestamp(time.time()))
'2015-04-06T23:56:30-0400'

- 696
- 4
- 10
This works for me:
if time.daylight > 0:
return time.altzone
else:
return time.timezone

- 2,900
- 1
- 22
- 25
-
it is incorrect. Notice: [`time.localtime().tm_isdst > 0` in a similar code in my answer](http://stackoverflow.com/a/3168394/4279) – jfs Sep 22 '15 at 22:59
-
Sorry, your post is so long and complete that I do not have understood that is the same answer. My post is surely a shorter version of the same solution. – Alecs Sep 23 '15 at 11:30
-
1no, the code is wrong. `time.daylight` does not say whether the summer time is right now. It says that the local time may have DST. That is why you have to call `time.localtime().tm_isdst` – jfs Sep 23 '15 at 12:57