Python datetime模塊的使用示例

1、獲取當前年月日時分秒

# -*- encoding=utf-8 -*-
import datetime
now = datetime.datetime.now()
print("now:{}".format(now))
year = now.year
print("year:{}".format(year))
month = now.month
print("month:{}".format(month))
day = now.day
print("day:{}".format(day))
hour = now.hour
print("hour:{}".format(hour))
minute = now.minute
print("minute:{}".format(minute))
second = now.second
print("second:{}".format(second))

2、datetime轉為string

# -*- encoding=utf-8 -*-
import datetime
now = datetime.datetime.now()
print('type:{}'.format(type(now)))
print('now datetime:{}'.format(now))
now_string = now.strftime('%Y-%m-%d %H:%M:%S')
print('type:{}'.format(type(now_string)))
print('now string:{}'.format(now_string))

3、string轉為datetime

# -*- encoding=utf-8 -*-
import datetime
time_str = '2021-01-28 10:51:26'
time_date = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('type:{}'.format(type(time_date)))
print(time_date)

4、時間相加

# -*- encoding=utf-8 -*-
import datetime
time_str = '2021-01-28 10:00:00'
time_date = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('原始時間:\t\t\t\t{}'.format(time_date))
add_info = datetime.timedelta(days=1, hours=2, minutes=3, seconds=4)
add_end = time_date + add_info
print('加上1天2個小時3分鐘4秒後:\t{}'.format(add_end))

 5、時間相減

①兩個時間差

# -*- encoding=utf-8 -*-
import datetime
time_str = '2021-01-28 10:00:00'
time_date = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('原始時間:\t{}'.format(time_date))
time_str = '2021-05-29 12:12:12'
time_date2 = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('原始時間2:\t{}'.format(time_date2))
time_date3 = time_date2 - time_date
print('時間差:{}'.format(time_date3))

②減去1天2個小時3分鐘4秒(加負數)

# -*- encoding=utf-8 -*-
import datetime
time_str = '2021-01-28 10:00:00'
time_date = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('原始時間:\t\t\t\t{}'.format(time_date))
add_info = datetime.timedelta(days=-1, hours=-2, minutes=-3, seconds=-4)
add_end = time_date + add_info
print('減去1天2個小時3分鐘4秒後:\t{}'.format(add_end))

以上就是Python datetime模塊的使用示例的詳細內容,更多關於Python datetime模塊的資料請關註WalkonNet其它相關文章!

推薦閱讀: