📜  python datetime with timezone - Python (1)

📅  最后修改于: 2023-12-03 15:33:59.057000             🧑  作者: Mango

Python DateTime with Timezone

Working with datetime and timezone in Python can be a bit tricky, especially if you're new to the language. This guide will cover the basics of working with datetime objects in Python, including how to work with timezone information.

Getting Started

First, let's start by importing the necessary modules:

import datetime
import pytz

We'll use the datetime module to work with dates and times, and the pytz module to work with timezones.

Creating a DateTime Object

To create a datetime object, we'll use the datetime.datetime constructor. This constructor takes multiple arguments, including the year, month, day, hour, minute, second, and microsecond.

# create a datetime object for January 1, 2022 at 12:00pm
dt = datetime.datetime(2022, 1, 1, 12, 0, 0)
Converting to a Different Timezone

To convert a datetime object to a different timezone, we'll use the pytz.timezone function.

# create a timezone object for US/Eastern
et = pytz.timezone('US/Eastern')

# convert our datetime object to US/Eastern
et_dt = et.localize(dt)
Displaying the DateTime Object

To display a datetime object in a specific format, we'll use the strftime method.

# display our datetime object in ISO format
print(et_dt.strftime('%Y-%m-%dT%H:%M:%S%z'))

This will output 2022-01-01T12:00:00-0500, which includes the year, month, day, hour, minute, second, and timezone in ISO format.

Conclusion

Working with datetime and timezone in Python can be a bit confusing, but with the datetime and pytz modules, it's easy to work with dates and times in any timezone. Whether you're building a web application or working on a data analysis project, understanding how to work with datetime and timezone information can be a valuable skill to have.