92

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')>))
Martin Thoma
  • 108,021
  • 142
  • 552
  • 849
Adam Matan
  • 117,979
  • 135
  • 375
  • 532
  • 1
    Exact duplicate of : http://stackoverflow.com/questions/117514/how-do-i-use-timezones-with-a-datetime-object-in-python – e-satis Sep 09 '09 at 10:13
  • Thanks. Didn't find it when I searched for the topic. – Adam Matan Sep 09 '09 at 10:57
  • 1
    Possible duplicate of [How do I use timezones with a datetime object in python?](https://stackoverflow.com/questions/117514/how-do-i-use-timezones-with-a-datetime-object-in-python) – Martin Thoma Apr 10 '18 at 13:48

11 Answers11

140

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')
jfs
  • 374,366
  • 172
  • 933
  • 1,594
Mark Theunissen
  • 2,306
  • 2
  • 16
  • 14
79

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'
Rob Bednark
  • 22,937
  • 20
  • 77
  • 112
Andre Miller
  • 14,667
  • 6
  • 52
  • 53
  • 3
    For the 'current time' part of the question, you could start with `loc_dt = pytz.utc.localize(datetime.utcnow())` instead of a constant – patricksurry Jan 18 '17 at 14:35
  • @patricksurry: the "current time" part is answered in [the most upvoted answer](https://stackoverflow.com/a/5096669/4279) – jfs May 15 '18 at 09:13
  • I dont want ot use external library. I want to use only native library. then how should I do? – Vikramsinh Gaikwad Aug 21 '20 at 13:06
  • 1
    In 2021 [this is the way to go](https://stackoverflow.com/a/63628816/6560549) – SuperShoot Feb 22 '21 at 02:41
  • Python 3.9+ has a new module in the **standard** library, called [zoneinfo](https://docs.python.org/3/library/zoneinfo.html). No need for external dependencies like [pytz](https://pypi.org/project/pytz/) anymore. – at54321 Oct 13 '21 at 07:36
27

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
FObersteiner
  • 16,957
  • 5
  • 24
  • 56
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'
Martin v. Löwis
  • 120,633
  • 17
  • 193
  • 234
10

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

Vinod
  • 121
  • 2
  • 7
7

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
htaccess
  • 2,174
  • 22
  • 24
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')
OLS
  • 135
  • 13
  • 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 '15 at 06: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"))
hooman
  • 486
  • 6
  • 19
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'),
SpiRail
  • 1,363
  • 17
  • 22
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!

autonopy
  • 312
  • 3
  • 8
-2

You can check this question.

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

Community
  • 1
  • 1
Guillem Gelabert
  • 2,645
  • 1
  • 20
  • 8