Fundamentals 18 min read

Comprehensive Guide to Python Time Handling with calendar, time, and datetime Modules

This article provides a detailed tutorial on Python's time‑related classes and functions, covering Unix timestamps, conversion tools, and the practical use of the calendar, time, and datetime modules with examples of formatting, timezone conversion, and common time‑conversion tricks for everyday programming tasks.

IT Services Circle
IT Services Circle
IT Services Circle
Comprehensive Guide to Python Time Handling with calendar, time, and datetime Modules

1. Timestamp

1.1 Timestamp Overview

Before diving into time functions we must understand the concept of a timestamp , specifically the unix timestamp, which counts seconds elapsed since 1970‑01‑01 00:00:00 UTC, ignoring leap seconds.

The Unix timestamp is widely used in databases (e.g., MySQL) and represents one hour as 3600 seconds and one day as 86400 seconds.

1.2 Timestamp Conversion Websites

Useful online tools for converting between timestamps and human‑readable dates include:

站长工具: https://tool.chinaz.com/tools/unixtime.aspx

在线工具: https://tool.lu/timestamp/

Json在线解析: https://www.sojson.com/unixtime.html

菜鸟工具: https://c.runoob.com/front-end/852

北京时钟: http://www.beijing-time.org/shijianchuo/

2. calendar Module

The calendar module ("日历") is suited for displaying dates in a calendar format.

2.1 Module Content

Example: display the calendar for the year 2020.

import calendar
year = calendar.calendar(2020)
print(year)

Changing parameters (w, l, c) adjusts column width, number of lines per week, and month spacing.

c: month spacing

w: column width

l: lines per week

Other useful functions:

calendar.isleap(year) – returns True if the year is a leap year.

calendar.leapdays(y1, y2) – counts leap years in the half‑open interval [y1, y2).

calendar.month(year, month, w=2, l=1) – returns a month calendar string.

calendar.monthcalendar(year, month) – returns a list of weeks, each week a list of day numbers (0 for days outside the month).

calendar.monthrange(year, month) – returns a tuple (first_weekday, number_of_days).

calendar.weekday(y, m, d) – returns the weekday (0=Monday … 6=Sunday).

3. time Module

The time module is the most commonly used module for time‑related operations.

3.1 Core Functions

time.time() – returns the current timestamp.

time.localtime([secs]) – converts a timestamp to a local struct_time tuple.

time.gmtime([secs]) – converts a timestamp to UTC struct_time .

time.asctime([t]) – formats a struct_time as a readable string.

time.ctime([secs]) – returns a readable string for a timestamp.

time.mktime(t) – converts a local struct_time to a timestamp.

time.strftime(fmt, t) – formats a struct_time according to fmt .

time.strptime(string, fmt) – parses a string into a struct_time using fmt .

3.2 Example

import time
now_timestamp = time.time()
now_tuple = time.localtime(now_timestamp)
print(time.strftime("%Y/%m/%d %H:%M:%S", now_tuple))

4. datetime Module

While time covers many needs, the datetime module offers richer objects for dates and times.

4.1 Key Classes

date – year, month, day.

time – hour, minute, second, microsecond.

datetime – combines date and time.

timedelta – represents a duration.

tzinfo – abstract base class for time‑zone information.

4.2 Using date

from datetime import date
today = date.today()
print("Current date:", today)
print("Weekday (0=Mon):", today.weekday())
print("ISO calendar:", today.isocalendar())

4.3 Using time (datetime.time)

from datetime import time
t = time(10, 20, 30, 40)
print(t.hour, t.minute, t.second, t.microsecond)

4.4 Using datetime

from datetime import datetime, date, time
print(datetime.today())
print(datetime.now())
print(datetime.utcnow())
print(datetime.fromtimestamp(1697302830))
print(datetime.combine(date(2020,12,25), time(11,22,54)))
print(datetime.strptime("2020-12-25", "%Y-%m-%d"))

4.5 Using timedelta

Represents a time span; supports weeks, days, hours, minutes, seconds, milliseconds, microseconds.

4.6 Timezone Handling with tzinfo

Example of converting UTC to Beijing (UTC+8) and Tokyo (UTC+9):

from datetime import datetime, timezone, timedelta
utc_now = datetime.utcnow().replace(tzinfo=timezone.utc)
beijing = utc_now.astimezone(timezone(timedelta(hours=8)))
tokyo = utc_now.astimezone(timezone(timedelta(hours=9)))
print(beijing)
print(tokyo)

5. Common Time Conversion Tricks

Timestamp → date

Date → timestamp

Formatting time strings

Getting the current time in a custom format

5.1 Timestamp to Date

import time
now_timestamp = time.time()
now_tuple = time.localtime(now_timestamp)
print(time.strftime("%Y/%m/%d %H:%M:%S", now_tuple))
# Specific timestamp example
timestamp = 1608852741
print(time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(timestamp)))

5.2 Date to Timestamp

import time
date_str = "2020-12-26 11:45:34"
date_array = time.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print(time.mktime(date_array))

5.3 Re‑formatting a Time String

import time
old = "2020-12-12 12:28:45"
time_array = time.strptime(old, "%Y-%m-%d %H:%M:%S")
new = time.strftime("%Y%m%d-%H:%M:%S", time_array)
print("Original:", old)
print("Reformatted:", new)

5.4 Custom Current‑Time Format

import time
now = time.time()
now_tuple = time.localtime(now)
formatted = time.strftime("%Y/%m/%d %H:%M:%S", now_tuple)
print(formatted)

6. Summary

This article thoroughly introduced Python's three main time‑related modules— calendar , time , and datetime —and demonstrated practical techniques for timestamp conversion, date formatting, and timezone handling, providing developers with essential tools to manage time in everyday programming tasks.

PythonprogrammingDateTimetimestampcalendartimedate-time conversion
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.