Python Date and Time Manipulation Examples
This article provides a comprehensive collection of Python code snippets demonstrating how to obtain, format, convert, calculate differences, and perform various operations with dates and times, including timers, scheduling, and weekday handling.
1. Get the current date and time
from datetime import datetime
now = datetime.now()
print("当前时间:", now)2. Format and output the current time
formatted_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print("格式化后的当前时间:", formatted_time)3. Calculate the number of days between two dates
from datetime import datetime
date1 = datetime(2025, 5, 1)
date2 = datetime(2025, 6, 1)
difference = (date2 - date1).days
print(f"{date1} 和 {date2} 之间相差 {difference} 天")4. Convert a string to a date object
from datetime import datetime
date_str = "2025-05-01"
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
print("日期对象:", date_obj)5. Convert a date object to a string
from datetime import datetime
date_obj = datetime.now()
date_str = date_obj.strftime("%Y-%m-%d")
print("日期字符串:", date_str)6. Get today's date
from datetime import date
today = date.today()
print("今天的日期:", today)7. Add one day to the current date
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)
print("明天的日期:", tomorrow)8. Subtract one hour from the current time
from datetime import datetime, timedelta
an_hour_ago = datetime.now() - timedelta(hours=1)
print("一小时前的时间:", an_hour_ago)9. Determine whether a year is a leap year
import calendar
year = 2024
if calendar.isleap(year):
print(f"{year} 是闰年")
else:
print(f"{year} 不是闰年")10. Get the first and last day of the current month
from datetime import datetime, timedelta
first_day = datetime.today().replace(day=1)
last_day = (first_day + timedelta(days=32)).replace(day=1) - timedelta(days=1)
print("本月第一天:", first_day.date())
print("本月最后一天:", last_day.date())11. Create a simple countdown timer
import time
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
t -= 1
countdown(5)
print("计时结束")12. Schedule a task using the sched module
import sched, time
scheduler = sched.scheduler(time.time, time.sleep)
def print_event(name):
print(f"事件: {name} 在 {time.time()} 执行")
print('开始:', time.time())
scheduler.enter(2, 1, print_event, ('事件1',))
scheduler.run()13. Get the calendar for a specific month
import calendar
year = 2025
month = 5
print(calendar.month(year, month))14. Convert a timestamp to a datetime
import time
from datetime import datetime
timestamp = time.time()
print("时间戳:", timestamp)
date_time = datetime.fromtimestamp(timestamp)
print("日期时间:", date_time)15. Convert a datetime to a timestamp
from datetime import datetime
date_time_str = '2025-05-05 12:00:00'
date_time_obj = datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S')
timestamp = date_time_obj.timestamp()
print("时间戳:", timestamp)16. Determine the day of the week for a given date
from datetime import datetime
date = datetime(2025, 5, 5)
print(date.strftime("%A")) # 输出星期几17. Calculate a date after adding a number of working days (excluding weekends)
from datetime import datetime, timedelta
def add_working_days(start_date, days):
current_date = start_date
added_days = 0
while added_days < days:
current_date += timedelta(days=1)
if current_date.weekday() < 5: # 排除周末
added_days += 1
return current_date
start_date = datetime(2025, 5, 5)
print(add_working_days(start_date, 10)) # 10个工作日后的日期18. Calculate the number of weeks between two dates
from datetime import datetime
date1 = datetime(2025, 5, 1)
date2 = datetime(2025, 6, 1)
weeks_difference = (date2 - date1).days // 7
print(f"{date1} 和 {date2} 之间相差 {weeks_difference} 周")19. Get the Monday and Sunday of the current week
from datetime import datetime, timedelta
today = datetime.today()
start_of_week = today - timedelta(days=today.weekday())
end_of_week = start_of_week + timedelta(days=6)
print("本周周一:", start_of_week.date())
print("本周周日:", end_of_week.date())20. Implement a simple delay using time.sleep()
import time
print("开始")
time.sleep(2) # 等待2秒
print("2秒后...")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.