Python timedelta()函數存在於datetime庫中,該函數通常用於計算日期差,也可以用於Python中的日期操作。這是執行日期操作的最簡單方法之一。
用法: datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
返回值:日期
代碼1:
# Timedelta function demonstration
from datetime import datetime, timedelta
# Using current time
ini_time_for_now = datetime.now()
# printing initial_date
print ("initial_date", str(ini_time_for_now))
# Calculating future dates
# for two years
future_date_after_2yrs = ini_time_for_now + \
timedelta(days = 730)
future_date_after_2days = ini_time_for_now + \
timedelta(days = 2)
# printing calculated future_dates
print('future_date_after_2yrs:', str(future_date_after_2yrs))
print('future_date_after_2days:', str(future_date_after_2days))
輸出:
initial_date 2019-02-27 12:41:45.018389 future_date_after_2yrs:2021-02-26 12:41:45.018389 future_date_after_2days:2019-03-01 12:41:45.018389
代碼2:
# Timedelta function demonstration
from datetime import datetime, timedelta
# Using current time
ini_time_for_now = datetime.now()
# printing initial_date
print ("initial_date", str(ini_time_for_now))
# Calculating past dates
# for two years
past_date_before_2yrs = ini_time_for_now - \
timedelta(days = 730)
# for two hours
past_date_before_2hours = ini_time_for_now - \
timedelta(hours = 2)
# printing calculated past_dates
print('past_date_before_2yrs:', str(past_date_before_2yrs))
print('past_date_after_2days:', str(past_date_before_2hours))
輸出:
initial_date 2019-02-27 12:41:46.104662 past_date_before_2yrs:2017-02-27 12:41:46.104662 past_date_after_2days:2019-02-27 10:41:46.104662
代碼3:
# Timedelta function demonstration
from datetime import datetime, timedelta
# Using current time
ini_time_for_now = datetime.now()
# printing initial_date
print ("initial_date", str(ini_time_for_now))
# Some another datetime
new_final_time = ini_time_for_now + \
timedelta(days = 2)
# printing new final_date
print ("new_final_time", str(new_final_time))
# printing calculated past_dates
print('Time difference:', str(new_final_time - \
ini_time_for_now))
輸出:
initial_date 2019-02-27 12:41:47.386595 new_final_time 2019-03-01 12:41:47.386595 Time difference:2 days, 0:00:00
相關用法
- Python now()用法及代碼示例
- Python cmp()用法及代碼示例
- Python map()用法及代碼示例
- Python ord()用法及代碼示例
- Python int()用法及代碼示例
- Python dir()用法及代碼示例
- Python hex()用法及代碼示例
- Python sum()用法及代碼示例
- Python tell()用法及代碼示例
- Python id()用法及代碼示例
- Python oct()用法及代碼示例
注:本文由純淨天空篩選整理自garg_ak0109大神的英文原創作品 Python | datetime.timedelta() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。