108

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')>))
3

12 Answers 12

145

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')
4
  • 2
    I dont want ot use external library. I want to use only native library. then how should I do? Aug 21, 2020 at 13:06
  • pytz and datetime are native libraries
    – David B.
    Oct 17, 2020 at 17:50
  • 4
    @DavidB. nope, pytz is a third party library. Luckily, zoneinfo comes with the standard lib of Python 3.9, see my answer ;-) Mar 26, 2021 at 15:13
  • Python 3.9+ has a new module in the standard library, called zoneinfo. No need for external dependencies like pytz anymore.
    – at54321
    Oct 13, 2021 at 7:36
84

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'
5
  • 3
    For the 'current time' part of the question, you could start with loc_dt = pytz.utc.localize(datetime.utcnow()) instead of a constant Jan 18, 2017 at 14:35
  • 1
    @patricksurry: the "current time" part is answered in the most upvoted answer
    – jfs
    May 15, 2018 at 9:13
  • I dont want ot use external library. I want to use only native library. then how should I do? Aug 21, 2020 at 13:06
  • 1
    In 2021 this is the way to go
    – SuperShoot
    Feb 22, 2021 at 2:41
  • Python 3.9+ has a new module in the standard library, called zoneinfo. No need for external dependencies like pytz anymore.
    – at54321
    Oct 13, 2021 at 7:36
46

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
2
  • 3
    whats the problem to usedatetime.now(tz=gettz('US/Pacific'))? Mar 26, 2021 at 13:46
  • 1
    @LeonardRick that's perfectly fine! Actually I wanted to add this option as well, never took the time. Thanks for the reminder ;-) Mar 26, 2021 at 14:36
16

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'
3
  • 3
    This only works in Unix according to the documentation. Not sure if that makes a difference here though. Sep 9, 2009 at 10:16
  • 2
    I needed a solution that doesn't use pytz and only needs to run on Linux systems, so this is perfect
    – Xandaros
    Jun 17, 2017 at 18:01
  • 3
    This one is perfectly working in AWS Lambda without pytz. Many thanks.
    – sid8491
    Jan 4, 2018 at 12:08
12

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

1
  • I dont want ot use external library. I want to use only native library. then how should I do? Aug 21, 2020 at 13:07
8

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
1
  • Why would you use pytz when you already have timezone?
    – Kebman
    Jul 30, 2021 at 19:44
2

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')
1
  • not different than previous one. only function formatted and cleaner look. I'll add it as a comment to it. oh... I cannot comment.
    – OLS
    Jul 12, 2015 at 6:55
1

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"))
2
  • Its 'Asia/Kolkata' not 'Asia/India', Get all available tzs: pytz.all_timezones Aug 18, 2020 at 4:56
  • @ShirishShukla Thanks for noticing. I have edited my answer to include Kolkata instead of India.
    – monkey
    Aug 22, 2020 at 15:12
0

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'),
0

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!

0

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.

1
-2

You can check this question.

Or try using pytz. Here you can find an installation guide with some usage examples.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.