Python datetime: 20 Common Date and Time Operations with Code Examples
This article presents twenty practical Python datetime examples covering current time retrieval, formatting, date arithmetic, leap year checks, timers, scheduling, calendar queries, timestamp conversions, and weekday calculations, each accompanied by clear code snippets for immediate use.
1. Get the current date and time:
from datetime import datetimenow = datetime.now()print("当前时间:", now)2. Format and print the current time:
formatted_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")print("格式化后的当前时间:", formatted_time)3. Calculate the difference in days between two dates:
from datetime import datetimedate1 = datetime(2025, 5, 1)date2 = datetime(2025, 6, 1)difference = (date2 - date1).daysprint(f"{date1} 和 {date2} 之间相差 {difference} 天")4. Convert a string to a datetime object:
from datetime import datetimedate_str = "2025-05-01"date_obj = datetime.strptime(date_str, "%Y-%m-%d")print("日期对象:", date_obj)5. Convert a datetime object to a string:
from datetime import datetimedate_obj = datetime.now()date_str = date_obj.strftime("%Y-%m-%d")print("日期字符串:", date_str)6. Get today's date:
from datetime import datetoday = date.today()print("今天的日期:", today)7. Add one day to the current date:
from datetime import datetime, timedeltanow = datetime.now()tomorrow = now + timedelta(days=1)print("明天的日期:", tomorrow)8. Subtract one hour from the current time:
from datetime import datetime, timedeltaan_hour_ago = datetime.now() - timedelta(hours=1)print("一小时前的时间:", an_hour_ago)9. Determine if a year is a leap year:
import calendaryear = 2024if 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, timedeltafirst_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 timedef countdown(t):while t:mins, secs = divmod(t, 60)timer = '{:02d}:{:02d}'.format(mins, secs)print(timer, end="\r")time.sleep(1)t -= 1countdown(5)print("计时结束")12. Schedule a task using the sched module:
import sched, timescheduler = 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. Print the calendar for a specific month:
import calendaryear = 2025month = 5print(calendar.month(year, month))14. Convert a timestamp to a datetime:
import timefrom datetime import datetimetimestamp = time.time()print("时间戳:", timestamp)date_time = datetime.fromtimestamp(timestamp)print("日期时间:", date_time)15. Convert a datetime string to a timestamp:
from datetime import datetimedate_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 weekday of a given date:
from datetime import datetimedate = 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, timedeltadef add_working_days(start_date, days):current_date = start_dateadded_days = 0while added_days < days:current_date += timedelta(days=1)if current_date.weekday() < 5: # 排除周末added_days += 1return current_datestart_date = datetime(2025, 5, 5)print(add_working_days(start_date, 10)) # 10个工作日后的日期18. Compute the number of weeks between two dates:
from datetime import datetimedate1 = datetime(2025, 5, 1)date2 = datetime(2025, 6, 1)weeks_difference = (date2 - date1).days // 7print(f"{date1} 和 {date2} 之间相差 {weeks_difference} 周")19. Get the Monday and Sunday of the current week:
from datetime import datetime, timedeltatoday = 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. Introduce a simple delay using time.sleep():
import timeprint("开始")time.sleep(2) # 等待2秒print("2秒后...")Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
