Home > Backend Development > Python Tutorial > How Can Python's pytz Library Display Time in Different Time Zones?

How Can Python's pytz Library Display Time in Different Time Zones?

Patricia Arquette
Release: 2024-12-25 10:56:45
Original
786 people have browsed it

How Can Python's pytz Library Display Time in Different Time Zones?

Displaying Time in Alternate Time Zones with Python's pytz

Introduction:

Many applications require converting and displaying time across different time zones. Determining the current time in any given zone can be a challenge without the right tools.

Solution:

The Python pytz library offers a convenient way to manipulate time zones and display time in a different time zone. The following is an elegant solution:

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'))
Copy after login

This code retrieves the current time in the South African time zone and prints it in the specified format.

Explanation:

  1. from datetime import datetime: Imports the datetime class.
  2. from pytz import timezone: Imports the timezone class.
  3. south_africa = timezone('Africa/Johannesburg'): Creates a timezone object for South Africa (using the 'Africa/Johannesburg' identifier).
  4. sa_time = datetime.now(south_africa): Retrieves the current time in the South African time zone.
  5. print(sa_time.strftime('%Y-%m-%d_%H-%M-%S')): Formats and prints the South African time in the specified format.

This method provides a straightforward and extensible way to display time in any desired time zone.

The above is the detailed content of How Can Python's pytz Library Display Time in Different Time Zones?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template