Python datetime module practical introduction and pitfall avoidance guide
Whether it is doing crawler storage and crawling records, Web backend processing order deadlines or user birthdays, or time series processing in data analysis, Python'sdatetimeThey are all standard library artifacts that cannot be avoided - no needpip install, ready to use right out of the box. This tutorial will help you quickly master its core functions and point out several common pitfalls for novices.
Core modules and classes sorting out
Let me first point out the most confusing detail for a novice: the module name isdatetime, there happens to be another class with the same name nested inside the moduledatetime. In order to make the code clearer, the following examples will accurately import the required classes to avoid confusion.
Get the current date and time
The most basic operation is to obtain the current time (local environment and time zone related content will be introduced later).
Customize creation date and time
Sometimes we don't need to take "now", but need to specify a specific year, month, day, or even accurate to hours, minutes, seconds, and microseconds.
Bidirectional conversion with timestamp
What is a timestamp?
The timestamp refers to the number of seconds calculated from January 1, 1970 00:00:00 UTC+0 (Greenwich Mean Time). What is returned in Python is a floating point number with microseconds. Its biggest advantage is that it is time zone independent - whether you are in Tokyo or New York, the timestamp of the same moment is exactly the same, so it is very suitable for persistent storage.
datetime to timestamp
Tips for avoiding pitfalls: local time zone impact
If createddttime zone is not explicitly set,timestamp()Automatically converts to UTC seconds using the local time zone of the running code. This may cause problems when running across environments (such as local Windows, server Linux), so be careful.
Convert timestamp to datetime
There are two commonly used methods, the difference is whether the datetime of "local time zone" or "UTC+0 time zone" is returned:
Bidirectional conversion with string
When we interact with users, files, and databases, what we most often see are human-readable strings instead of datetime objects. In this case, bidirectional conversion is required.
Convert string to datetime (parsing)
usestrptime()Method for parsing, the core point is to strictly match the format character, the format character must exactly match the string, otherwise an error will be reported.
Cheat Sheet for Commonly Used Format Characters
Convert datetime to string (formatting)
usestrftime()Method, also using the above format characters, can flexibly customize the output style.
Date and time addition and subtraction operations
Want to calculate "deadline in 3 days" or "crawl time 2 hours ago"? Need to use at this timetimedeltakind. it means twodatetimeThe time difference between them supports the addition and subtraction of days, hours, minutes, seconds and microseconds.
Simple time zone processing
Python 3.2 and above have built-intimezoneclass, coordinationtimedeltaIt can handle basic time zone requirements.
Explicitly set the time zone of datetime
As mentioned in the previous pit avoidance tips, the default createddatetimeThere are no time zone markers. we can usereplace()method, or directly innow()incomingtzinfoparameters to set the time zone.
Conversion between time zones
useastimezone()Method to implement time zone conversion, provided that the original datetime object already carries the time zone mark.
Best Practice Summary
- Prefer to use timestamp or UTC datetime with time zone when storing: time zone independent, safe and stable across environments.
- Convert to user time zone during display: For example, the web backend reads the time zone preference of the user's browser, converts it, and then returns it to the front end for display.
- Format characters must be strictly matched when parsing with strptime: no space or punctuation mark will be missed.
Small exercise: Convert string with time zone to timestamp
Using the knowledge you learned earlier, try writing a small function to convert a date string with time zone information into a timestamp. This uses the built-in Python 3.9+zoneinfomodule, which is more intuitive to handle.
By mastering the above core functions, you can easily handle 90% of the date and time processing needs in daily development.

