Skip to content

Using datetime to Deal with Time in Python

Introduction

Python is a powerful programming language widely used for various programming tasks, including data analysis, web development, and machine learning. One of the essential aspects of programming is dealing with date and time. Python provides a powerful built-in module called datetime that makes dealing with time easier and more efficient. In this post, we will explore how to use the datetime module to handle time in Python.

Converting Dates

The datetime module includes several classes that can be used to represent dates, times, and combinations of the two. One of the most commonly used classes is the date class, which represents a date in the format year-month-day. To create a date object, we can use the date() method. For example, the following code creates a date object that represents January 1, 2022:

from datetime import date

d = date(2022, 1, 1)
print(d)

Output:

2022-01-01

Formatting Dates

The datetime module also provides several methods for formatting dates as strings. For example, the strftime() method can be used to format a date object as a string in a specific format. The method takes a format string as an argument and returns a string representing the date in the specified format. For example, the following code formats the date object d created in the previous example as a string in the format Month Day, Year:

from datetime import date

d = date(2022, 1, 1)
formatted_date = d.strftime("%B %d, %Y")
print(formatted_date)

Output:

January 01, 2022

Using Time Zones

Dealing with time zones can be tricky, but the datetime module makes it easier by providing a timezone class. We can use the timezone class to create a time zone object and use it to convert between time zones. For example, the following code creates a timezone object for the Eastern Time Zone (US) and converts a datetime object to that time zone:

from datetime import datetime, timezone
import pytz

dt = datetime(2022, 1, 1, 12, 0, 0)
utc_dt = dt.replace(tzinfo=timezone.utc)
eastern_dt = utc_dt.astimezone(pytz.timezone('US/Eastern'))
print(eastern_dt)

Output:

2022-01-01 07:00:00-05:00

Conclusion

The datetime module in Python provides a powerful and efficient way to work with dates and times. In this post, we explored how to create date objects, format dates as strings, and work with time zones. With this knowledge, you can now handle time-related tasks more efficiently in your Python programming projects.

Reference

from datetime import datetime, timezone
import time

## UTC --> local time
now = datetime.now()
now_utc = now.replace(tzinfo=timezone.utc)
now_local = now_utc.astimezone()
print(now_local)

## UTC --> UNIX timestamp
time_str = str(now_local).split(".")[0]
time_format = '%Y-%m-%d %H:%M:%S'
now = datetime.strptime(time_str, time_format)
time_tuple = now.timetuple()
utc_now = time.mktime(time_tuple)
print(utc_now)

## switch time zone
import pytz
arrival_nyc = str(now_local).split(".")[0]
nyc_dt_naive = datetime.strptime(arrival_nyc, time_format)
eastern = pytz.timezone('US/Eastern')
nyc_dt = eastern.localize(nyc_dt_naive)
utc_dt = pytz.utc.normalize(nyc_dt.astimezone(pytz.utc))
print(utc_dt)
Feedback