Time is intangible, yet it flows through every line of code you write: logs are stamped with it, tasks are triggered by it, and reports are organized around it…

Today, let’s wrap up the 8 most essential date-time handling tricks in Python in the time it takes to finish a cup of coffee!
First, Meet the Two Core Libraries
Date and time operations in Python are dominated by two official libraries:
- time: Introduced with Python 1.4 in 1996
- A low-level stopwatch that handles timestamps and pauses threads, but cannot perform date arithmetic and does not support daylight saving time.
- datetime: Added in Python 2.3 in 2003
- A high-level calendar tool that encapsulates year-month-day-hour-minute-second into objects. You can add 30 days, subtract 2 hours, or switch timezones with just one line of code.
In a nutshell: The time library manages seconds, while datetime manages days. For daily development, 90% of requirements can be handled by datetime. Use time only for the remaining 10% of cases that require second-level precision or interaction with the operating system.
8 High-Frequency Use Cases
Scenario 1: Get Current Date/Time
Sample code:
python
from datetime import datetime
# Method 1: Year-Month-Day Hour:Minute:Second:Microsecond
now = datetime.now()
print(now)
# Output: 2025-07-13 14:30:15.123456
# Method 2: Only Date (Year-Month-Day)
today = datetime.now().date()
print(today)
# Output: 2025-07-13
# Method 3: Only Time (Hour:Minute:Second:Microsecond)
current_time = datetime.now().time()
print(current_time)
# Output: 14:30:15.123456
Note: strftime is like a magic time formatter that converts date objects into strings in any format you need.
Scenario 2: Pause Program Execution for Seconds
python
import time
print("Start")
time.sleep(3) # Wait for 3 seconds
print("Resume after 3 seconds")
Note: time.sleep(3) pauses the current thread for 3 seconds. The operating system will wake it up after 3 seconds to continue executing subsequent code.
Scenario 3: Measure Code Execution Time
python
import time
# Get start timestamp
start = time.perf_counter()
# Simulate time-consuming operation
sum = 0
for i in range(1000000):
sum += i
end = time.perf_counter()
print(f"Execution Time: {end - start:.4f} seconds")
# Output: Execution Time: 0.0453 seconds
Note: You can also use time.time() for this purpose, but perf_counter() offers higher precision and is not affected by system clock adjustments, making it more suitable for measuring time intervals.
Both time.time() and perf_counter() return timestamps: Python reads the current system time, converts it to the number of seconds elapsed since UTC 1970-01-01 00:00:00, and returns it as a float (e.g., timestamp: 1689345123.123456).
Scenario 4: Generate Custom Time Formats (e.g., Year-Month-Day)
python
from datetime import datetime
now = datetime.now()
# Convert to "2025年07月13日 14:30" format
formatted = now.strftime("%Y年%m月%d日 %H:%M")
print(formatted)
# Convert to "Aug 20, 2023" format
english_style = now.strftime("%b %d, %Y")
print(english_style)
📝 Common Placeholder Reference:
| Placeholder | Description | Example Output |
|---|---|---|
%Y | 4-digit year | 2025 |
%m | 2-digit month (01-12) | 07 |
%d | 2-digit day (01-31) | 15 |
%H | 24-hour format hour (00-23) | 14 |
%I | 12-hour format hour (01-12) | 02 |
%M | 2-digit minute (00-59) | 30 |
%S | 2-digit second (00-59) | 45 |
%A | Full weekday name | Monday |
%a | Abbreviated weekday name | Mon |
Scenario 5: Create Custom Time Objects
python
from datetime import datetime
# Create a date object in "2025-07-13" format
date_obj = datetime.strptime("2025-07-13", "%Y-%m-%d").date()
print(date_obj) # 2025-07-13
print(type(date_obj))
# <class 'datetime.date'>
# Create a time object in "14:30:00" format
time_obj = datetime.strptime("14:30:00", "%H:%M:%S").time()
print(time_obj) # 14:30:00
# Create a combined date-time object
log_time = datetime.strptime("2025-07-13 14:30:15", "%Y-%m-%d %H:%M:%S")
print(log_time) # 2025-07-13 14:30:15
You can also use the date class to create date objects:
python
from datetime import date
d1 = date(2025, 9, 1)
d2 = date(2025, 9, 5)
# The date class is more convenient for date-only operations
print((d2 - d1).days)
# Output: 4 days
📝 Note: When constructing dates, pay attention to valid ranges (e.g., February cannot have 30 days, and there is no 13th month). Invalid dates will throw errors.
Scenario 6: Perform Date Arithmetic
python
from datetime import datetime, timedelta
# Calculate the time 10 days later
today = datetime.today()
future = today + timedelta(days=10)
print("10 Days Later:", future)
# Calculate the time 2 hours ago
past = datetime.now() - timedelta(hours=2)
print(past)
# Calculate the interval between two dates
birth1 = datetime(2000, 2, 29)
birth2 = datetime(2024, 2, 29)
print("Days Between:", (birth2 - birth1).days)
📝 Note: timedelta is the “ruler” for date arithmetic. It supports multiple units including days, hours, minutes, seconds, and microseconds, which can be combined flexibly.
Scenario 7: Get Specific Dates (e.g., First Day of the Month / First Day of the Week)
python
from datetime import datetime, timedelta, date
# Get the first day of the current month
first_day = datetime.now().replace(day=1)
# Get the last day of the current month (28+5 days will definitely reach next month)
# Trick: Subtract 1 day from the first day of the next month
next_month = datetime.now().replace(day=28) + timedelta(days=5)
last_day = next_month.replace(day=1) - timedelta(days=1)
# Get Monday of the current week
today = datetime.now()
monday = today - timedelta(days=today.weekday())
Note: replace() returns a new object with specified fields (year, month, day, hour, minute, second) adjusted. The weekday() function returns the day of the week as an integer: Monday = 0, Sunday = 6.
Scenario 8: Switch Between Global Timezones with One Line of Code
python
from datetime import datetime
from zoneinfo import ZoneInfo
tokyo_time = datetime.now(ZoneInfo("Asia/Tokyo"))
print("Tokyo Time:", tokyo_time.strftime("%Y-%m-%d %H:%M:%S"))
Note: The zoneinfo module is built into Python 3.9 and above. For lower versions, you need to install it via pip. By default, it reads the timezones configured on the operating system. Pass a timezone object (ZoneInfo()) to easily switch clocks worldwide (e.g., Beijing Time: Asia/Shanghai, New York Time: America/New_York).
Quick Reference Cheat Sheet
| Requirement | Recommended API |
|---|---|
| Get current time | datetime.now() |
| String to date | datetime.strptime() |
| Date to string | .strftime() |
| Date arithmetic | timedelta |
| Measure execution time | time.perf_counter() |
| Timezone conversion | ZoneInfo("Area/City") |
Conclusion
Bookmark this article in your browser! Next time you encounter any date/time requirements, just copy and paste the code directly!