Master Python Time Handling: Timestamps, Calendar, datetime & Practical Tricks
This article provides a comprehensive guide to Python's time-related modules—including timestamps, the calendar module, time, and datetime—explaining core concepts, useful functions, and real‑world examples, plus handy conversion techniques for everyday programming tasks.
In daily life and work we constantly interact with time, facing questions such as when to wake up, subway intervals, lunch breaks, weekdays, and adding scheduled tasks to code. This article explains Python's time‑related classes, methods, and attributes in detail.
1. Timestamp
1.1 Timestamp Overview
A timestamp is the number of seconds elapsed since 1970‑01‑01 UTC (Unix timestamp). It is used to ensure data ordering and consistency across systems.
Unix timestamps count seconds without leap seconds; one hour equals 3600 seconds, one day equals 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/
After covering timestamps, we focus on three Python libraries for date and time handling: calendar, time, and datetime.
2. calendar
The calendar module provides calendar‑style date displays.
2.1 Module Content
Example: display the calendar for 2020.
import calendar
year = calendar.calendar(2020)
print(year)Changing parameters adjusts width and layout:
year = calendar.calendar(2020, w=3, l=1, c=8)
print(year)Parameters meaning:
c: month spacing
w: day column width
l: number of rows 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 interval [y1, y2). calendar.month(year, month, w=2, l=1): returns a string calendar for a specific month. 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 (weekday of first day, number of days in month). calendar.weekday(y, m, d): returns the weekday (0‑6, Monday‑Sunday).
3. time
The time module is the most commonly used module for time operations.
3.1 Core Functions
time.time(): current timestamp. time.localtime([secs]): convert a timestamp to a time tuple (local time). time.gmtime([secs]): convert a timestamp to a UTC time tuple. time.asctime([t]): format a time tuple as a readable string. time.ctime([secs]): convert a timestamp to a readable string. time.mktime(t): convert a local time tuple to a timestamp. time.strftime(fmt, t): format a time tuple according to fmt. time.strptime(string, fmt): parse a string into a time tuple.
3.2 Example Usage
import time
now_timestamp = time.time()
now_tuple = time.localtime(now_timestamp)
print(time.strftime("%Y/%m/%d %H:%M:%S", now_tuple))Converting a specific timestamp:
timestamp = 1608852741
t = time.localtime(timestamp)
print(time.strftime("%Y/%m/%d %H:%M:%S", t))4. datetime
When time is insufficient, the datetime module offers richer functionality.
4.1 Key Classes
date: year, month, day. time: hour, minute, second, microsecond. datetime: combination of date and time. timedelta: duration between two dates/times. tzinfo: time‑zone information.
4.2 Example: Working with date
from datetime import date
today = date.today()
print("Current date:", today)
print("Year:", today.year)
print("Month:", today.month)
print("Day:", today.day)
print("Weekday (0=Mon):", today.weekday())4.3 Example: Working with datetime
from datetime import datetime, time, timezone, timedelta
# Current datetime
print(datetime.now())
# From timestamp
print(datetime.fromtimestamp(1697302830))
# Combine date and time
combined = datetime.combine(date(2020,12,25), time(11,22,54))
print(combined)
# Formatting
print(combined.strftime("%Y-%m-%d %H:%M:%S"))4.4 Timezone Conversion
from datetime import datetime, timezone, timedelta
utc_now = datetime.utcnow().replace(tzinfo=timezone.utc)
beijing = utc_now.astimezone(timezone(timedelta(hours=8)))
print(beijing)5. Common Time Conversion Techniques
Timestamp to date.
Date to timestamp.
Formatting time.
Getting the current time in a specific 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))5.2 Date to Timestamp
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 Reformatting Time
old = "2020-12-12 12:28:45"
arr = time.strptime(old, "%Y-%m-%d %H:%M:%S")
new = time.strftime("%Y%m%d-%H:%M:%S", arr)
print(new)5.4 Getting Current Time in a Custom 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
The article thoroughly introduces Python's three main modules for time output and conversion— calendar, time, and datetime —and summarizes four practical conversion tricks to help developers handle time data efficiently.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
