需引入datetime和timezone基础库,本章只列出一些常用的函数。 一、时间转换 1.1、基础操作 from datetime import timedelta #定义时间 a = timedelta ( days = 2 , hours = 6 ) b = timedelta ( hours = 4.5 ) print (
需引入datetime和timezone基础库,本章只列出一些常用的函数。
一、时间转换
1.1、基础操作
from datetime import timedelta#定义时间
a = timedelta(days=2, hours=6)
b = timedelta(hours=4.5)
print(a) # 2 days, 6:00:00
c = a + b
print(f'{a} + {b} = {c}') # 2 days, 6:00:00 + 4:30:00 = 2 days, 10:30:00
#取得各组成部分
print(f'c.days = {c.days}') #2
print(f'c.seconds = {c.seconds}') # 37800
print(f'c.seconds / 3600 = {c.seconds / 3600}') #10.5
print(f'c.total_seconds() / 3600 = {c.total_seconds() / 3600}') #58.5
1.2、计算
from datetime import timedeltafrom datetime import datetime
a = datetime(2020, 1, 1)
b = datetime(2020, 4, 28)
print(f'{a} + timedelta(days=10) = {a + timedelta(days=10)}') #2020-01-11 00:00:00
d = b - a
print(f'd.days = {d.days}') #118
now_date = datetime.today()
print(f'the date time of now is: {now_date}') #2022-06-20 16:51:20.161591
print(f'{now_date} + timedelta(minutes=30) = {now_date + timedelta(minutes=30)}') #2022-06-20 17:21:20.161591 ||months=1from datetime import datetime
a = datetime(2020, 1, 1)
b = datetime(2020, 4, 28)
from dateutil.relativedelta import relativedelta
print(f'{a} + relativedelta(months=+1) = {a + relativedelta(months=+1)}') #2020-02-01 00:00:00
print(f'{a} + relativedelta(months=+4) = {a + relativedelta(months=+4)}') #2020-05-01 00:00:00
二、与字符串互转
from datetime import datetimedate_text = '2020-04-20'
y = datetime.strptime(date_text, '%Y-%m-%d')
z = datetime.now()
print(f'z = {z}') #2022-06-20 16:56:20.573184
print(f'{z} - {y} = {z - y}') #791 days, 16:56:20.573184
print(f"datetime.strftime(z, '%A %B %d, %Y') = {datetime.strftime(z, '%A %B %d, %Y')}") #Monday June 20, 2022
from datetime import datetime
def parse_ymd(s):
year_s, mon_s, day_s = s.split('-')
return datetime(int(year_s), int(mon_s), int(day_s))
print(parse_ymd('2012-12-21')) #2012-12-21 00:00:00
三、时区
from datetime import datetimefrom pytz import timezone
date_time = datetime(2020, 4, 28, 9, 30, 0)
print(f'current is: {date_time}') #2020-04-28 09:30:00
central = timezone('US/Central')
chicage_date = central.localize(date_time)
print(f'chicage date is: {chicage_date}') #2020-04-28 09:30:00-05:00
chine_d = chicage_date.astimezone(timezone('Asia/Shanghai'))
print(f'chine date is: {chine_d}') #2020-04-28 22:30:00+08:00
from datetime import timedelta
import pytz
utc_d = chicage_date.astimezone(pytz.utc)
print(f'utc_d is: {utc_d}') #2020-04-28 14:30:00+00:00
print(f"country timezone is:{pytz.country_timezones['CN']}") #['Asia/Shanghai', 'Asia/Urumqi']