- Display the time in a different time zone
- 12 Answers 12
- How to preserve the timezone information in Python datetime strptime() and strftime()?
- Method 1: Use the pytz library
- Step 1: Import the necessary libraries
- Step 2: Create a timezone-aware datetime object
- Step 3: Convert the datetime object to a string with timezone information
- Step 4: Convert the string back to a timezone-aware datetime object
- Step 5: Convert the datetime object to a different timezone
- Method 2: Use the dateutil library
- Method 3: Use the datetime.strptime() method with a format string that includes the timezone
- Method 4: Use the datetime.strftime() method with the %z directive
- Tags:
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 = print("Local time <>".format(cur)) print("Pacific time <>".format()) print("Israeli time <>".format())
12 Answers 12
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')
@DavidB. nope, pytz is a third party library. Luckily, zoneinfo comes with the standard lib of Python 3.9, see my answer 😉
Python 3.9+ has a new module in the standard library, called zoneinfo. No need for external dependencies like pytz anymore.
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'
For the ‘current time’ part of the question, you could start with loc_dt = pytz.utc.localize(datetime.utcnow()) instead of a constant
Python 3.9+ has a new module in the standard library, called zoneinfo. No need for external dependencies like pytz anymore.
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 ") print(f"Pacific time ") # 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 ") print(f"UTC ") # Local time 2021-03-26T16:09:18+01:00 # I'm on Europe/Berlin # UTC 2021-03-26T15:09:18+00:00
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 ") print(f"Pacific time ") # Israeli time 2021-03-26T18:09:18+03:00 # Pacific time 2021-03-26T08:09:18-07:00
@LeonardRick that’s perfectly fine! Actually I wanted to add this option as well, never took the time. Thanks for the reminder 😉
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'
This only works in Unix according to the documentation. Not sure if that makes a difference here though.
The shortest ans of the question can be like:
from datetime import datetime import pytz print(datetime.now(pytz.timezone('Asia/Kolkata')))
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()))
$ ./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')
not different than previous one. only function formatted and cleaner look. I’ll add it as a comment to it. oh. I cannot comment.
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"))
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.
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
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'),
How to preserve the timezone information in Python datetime strptime() and strftime()?
The datetime module in Python provides the strptime() and strftime() methods for parsing and formatting date strings, respectively. However, when working with timezone-aware datetime objects, the timezone information is not preserved by default when using these methods. This can lead to unexpected results when working with timestamps from different timezones. In this article, we will explore several ways to preserve the timezone information when using strptime() and strftime() in Python.
Method 1: Use the pytz library
To preserve timezone information while working with datetime objects in Python, we can use the pytz library. The pytz library allows us to work with timezone-aware datetime objects and convert them to different timezones.
Here are the steps to preserve timezone information using pytz:
Step 1: Import the necessary libraries
from datetime import datetime import pytz
Step 2: Create a timezone-aware datetime object
utc = pytz.utc datetime_utc = datetime.now(tz=utc)
Step 3: Convert the datetime object to a string with timezone information
datetime_str = datetime_utc.strftime('%Y-%m-%d %H:%M:%S %Z')
Step 4: Convert the string back to a timezone-aware datetime object
datetime_obj = datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S %Z')
Step 5: Convert the datetime object to a different timezone
pst = pytz.timezone('US/Pacific') datetime_pst = datetime_obj.astimezone(pst)
Here is the complete code:
from datetime import datetime import pytz utc = pytz.utc datetime_utc = datetime.now(tz=utc) datetime_str = datetime_utc.strftime('%Y-%m-%d %H:%M:%S %Z') datetime_obj = datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S %Z') pst = pytz.timezone('US/Pacific') datetime_pst = datetime_obj.astimezone(pst)
This code will create a timezone-aware datetime object, convert it to a string with timezone information, convert the string back to a timezone-aware datetime object, and finally convert it to a different timezone.
We can use this approach to preserve timezone information while working with datetime objects in Python.
Method 2: Use the dateutil library
To preserve timezone information when using strptime() and strftime() in Python, the dateutil library can be used. Here are the steps to do it:
pip install python-dateutil
from dateutil import parser from dateutil import tz
dt_str = "2022-01-01T00:00:00-05:00" dt = parser.parse(dt_str)
new_tz = tz.gettz("Europe/London") dt_new_tz = dt.astimezone(new_tz)
dt_new_tz_str = dt_new_tz.strftime("%Y-%m-%dT%H:%M:%S%z")
Here is the complete code:
from dateutil import parser from dateutil import tz dt_str = "2022-01-01T00:00:00-05:00" dt = parser.parse(dt_str) new_tz = tz.gettz("Europe/London") dt_new_tz = dt.astimezone(new_tz) dt_new_tz_str = dt_new_tz.strftime("%Y-%m-%dT%H:%M:%S%z")
This code will parse the datetime string with timezone information, convert it to the desired timezone, and format it with timezone information using strftime() .
Method 3: Use the datetime.strptime() method with a format string that includes the timezone
To preserve the timezone information when using the datetime.strptime() method, you can include the timezone in the format string. Here's an example:
from datetime import datetime date_string = '2022-06-01 12:00:00+05:30' date_format = '%Y-%m-%d %H:%M:%S%z' date_obj = datetime.strptime(date_string, date_format) print(date_obj)
In this example, the %z format code is used to include the timezone information in the format string. The date_string variable contains a date string with timezone information in the format YYYY-MM-DD HH:MM:SS+HH:MM . The date_format variable contains the format string with %z included to represent the timezone.
The datetime.strptime() method parses the date string using the provided format string and returns a datetime object with the timezone information preserved.
You can also use the strftime() method to format the datetime object with the timezone information. Here's an example:
date_format = '%Y-%m-%d %H:%M:%S %Z' formatted_date = date_obj.strftime(date_format) print(formatted_date)
In this example, the %Z format code is used to include the timezone abbreviation in the format string. The date_format variable contains the format string with %Z included to represent the timezone abbreviation.
The strftime() method formats the datetime object using the provided format string and returns a formatted date string with the timezone information included.
Overall, by including the timezone information in the format string when using datetime.strptime() , you can preserve the timezone information in the resulting datetime object. Similarly, by including the timezone abbreviation in the format string when using strftime() , you can format the datetime object with the timezone information.
Method 4: Use the datetime.strftime() method with the %z directive
To preserve timezone information when converting datetime objects to strings using strftime(), you can use the %z directive. This directive represents the UTC offset of the timezone. Here's an example:
import datetime dt = datetime.datetime(2021, 6, 1, 12, 0, tzinfo=datetime.timezone.utc) dt_str = dt.strftime("%Y-%m-%d %H:%M:%S%z") print(dt_str) # output: 2021-06-01 12:00:00+0000
In this example, we create a datetime object with timezone information using the datetime.timezone.utc timezone. We then use the strftime() method with the %z directive to convert the datetime object to a string with timezone information.
import datetime dt = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=-7))) dt_str = dt.strftime("%Y-%m-%d %H:%M:%S%z") print(dt_str) # output: 2021-06-01 12:00:00-0700
In this example, we create a datetime object with timezone information using the datetime.timezone() method and passing in a datetime.timedelta() object with a negative number of hours to represent a timezone offset of -7 hours. We then use the strftime() method with the %z directive to convert the datetime object to a string with timezone information.
Overall, using the %z directive with strftime() is a simple and effective way to preserve timezone information when converting datetime objects to strings.