Python datetime tutorial: current time, timestamps, date arithmetic, formatting, parsing, range generation, and calendar display
This tutorial demonstrates how to use Python's datetime and calendar modules to obtain the current date and time, convert dates to timestamps, perform date arithmetic, format and parse dates, generate date ranges, compare dates, and display monthly calendars, with clear code examples for each operation.
1. Get the current date and time
from datetime import datetime
# 获取当前的日期和时间
now = datetime.now()
print("当前的日期和时间:", now)Output example: 当前的日期和时间: 2024-08-08 14:30:22.123456
2. Get the timestamp of a specific date
from datetime import datetime
# 将字符串转换为日期对象
date_str = "2024-08-08"
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
# 转换为时间戳
timestamp = date_obj.timestamp()
print("时间戳:", timestamp)Output example: 时间戳: 1691510400.0
3. Date addition and subtraction
from datetime import datetime, timedelta
# 当前日期
today = datetime.now().date()
# 明天的日期
tomorrow = today + timedelta(days=1)
print("明天的日期:", tomorrow)
# 一周前的日期
last_week = today - timedelta(weeks=1)
print("一周前的日期:", last_week)Output example: 明天的日期: 2024-08-09 一周前的日期: 2024-08-01
4. Date formatting
from datetime import datetime
# 当前日期
today = datetime.now()
# 格式化日期
formatted_date = today.strftime("%Y-%m-%d %H:%M:%S")
print("格式化后的日期:", formatted_date)Output example: 格式化后的日期: 2024-08-08 14:30:22
5. Calculate the difference between two dates
from datetime import datetime
# 创建两个日期对象
date1 = datetime(2024, 8, 8)
date2 = datetime(2024, 8, 15)
# 计算差值
delta = date2 - date1
print("两个日期之间的差值:", delta.days, "天")Output example: 两个日期之间的差值: 7 天
6. Compare two dates
from datetime import datetime
# 创建两个日期对象
date1 = datetime(2024, 8, 8)
date2 = datetime(2024, 8, 15)
# 比较日期
if date1 < date2:
print("date1 在 date2 之前")
else:
print("date1 不在 date2 之前")Output example: date1 在 date2 之前
7. Parse a date string
from datetime import datetime
# 定义日期字符串
date_str = "2024-08-08 14:30:22"
# 解析日期字符串
date_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print("解析后的日期对象:", date_obj)Output example: 解析后的日期对象: 2024-08-08 14:30:22
8. Generate all dates within a range
from datetime import datetime, timedelta
# 定义开始和结束日期
start_date = datetime(2024, 8, 8)
end_date = datetime(2024, 8, 15)
# 生成日期范围内的所有日期
current_date = start_date
while current_date <= end_date:
print(current_date.strftime("%Y-%m-%d"))
current_date += timedelta(days=1)Output example: 2024-08-08 2024-08-09 2024-08-10 2024-08-11 2024-08-12 2024-08-13 2024-08-14 2024-08-15
9. Determine if a date belongs to a specific month
from datetime import datetime
# 定义日期
date_obj = datetime(2024, 8, 15)
# 判断日期是否属于8月份
if date_obj.month == 8:
print("日期属于8月份")
else:
print("日期不属于8月份")Output example: 日期属于8月份
10. Display a monthly calendar using the calendar module
import calendar
# 打印2024年8月份的日历
print(calendar.month(2024, 8))Output example: August 2024 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Test Development Learning Exchange
Test Development Learning Exchange
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.