显示不同时区的时间

是否有一种优雅的方式来显示另一个时区的当前时间?

我想要一些具有以下总体精神的东西:

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')>))
114695 次浏览

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'

You can check this question.

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

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'

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

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

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

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

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

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"))

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

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!

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.