Introducing Python standard library datetime
Time Concepts
Need to clarify several concepts first
- Physical time: Physical concept time, continuously flowing time
- Timestamp: Offset from January 1, 1970, 0:00:00 of Coordinated Universal Time (UTC).
- UTC time: Based on atomic time second length, as close as possible to Greenwich Mean Time in time.
- Timezone: How many hours offset from UTC time, for example Beijing is in UTC+8 timezone, time is UTC time plus 8 hours,
- Time string: Human-readable string representing time.
- RFC 2822: Form like
Tue, 1 Jul 2003 10:52:37 +0200
- RFC 3339: Form like
1996-12-19T16:39:57-08:00
- ISO 8601: Difference from RFC 3339 see RFC3339-ISO8601
- RFC 2822: Form like
If Beijing time January 1, 2023, 8 o’clock. This 8 o’clock refers to 8 o’clock in UTC+8 timezone. Corresponding UTC time is January 1, 2023, 0 o’clock. Corresponding millisecond timestamp is 1672531200000. RFC3339 string is 2023-01-01T08:00:00+08:00
Concept memory progression as follows:
Physical time -> Timestamp -> UTC time -> Time with timezone information
Examples
Class names in datetime module are not capitalized. And there is a datetime class, class name exactly same as module name, easily confused. When using, note: from datetime import datetime
. Will import datetime class from datetime module. If directly import datetime
, will import module, need to use datetime.datetime
to represent datetime class
from datetime import datetime,timedelta
# Get current time. Below are all class methods
print(datetime.utcnow())
print(datetime.now()) # Current timezone time, return type is datetime class
print(datetime.now().timestamp()) # Output float timestamp, before decimal point is seconds, after is milliseconds
# Time addition and subtraction
now = datetime.now()
now + timedelta(hours=8) # Add 8 hours
# Mutual conversion with time strings
nowstr = now.strftime('%Y-%m-%d %H:%M:%S') # strftime is str format time abbreviation
now = datetime.strptime('2023-06-26 00:59:15','%Y-%m-%d %H:%M:%S')
## Convert from rfc3339 string to datetime
rfc3339_str = "2023-06-25T14:30:00.000Z"
datetime.fromisoformat(rfc3339_str)
datetime Module Source Code Explanation
datetime module source code Inheritance relationship as follows
object
timedelta # This class represents time interval
tzinfo
timezone # Timezone information
time
date # Date
datetime # Date + time