1. 程式人生 > >python之 datetime模組

python之 datetime模組

datetime是python處理時間和日期的標準庫.

1.基本物件

from datetime import datetime
datetime.time()   #時,分,秒,微秒 自動轉換成str字串    與 _repr_不一樣
datetime.date()    #年,月,日
datetime.datetime()  ##########年,月,日,時,分,秒,微秒    (最常用)

# 例子
t= datetime.time(20,30,1,2)
print('str:',t)    #str: 20:30:01.000002   預設自動轉換成str
print('repr',repr(t))   #repr datetime.time(20, 30, 1, 2)

2.實用函式

# 當前日期時間: 
datetime.datetime.now()

# 當前UTC日期時間:
datetime.datetime.utcnow()

# 時間戳轉日期時間:
datetime.datetime.fromtimestamp(ts)
# 例子
ts = datetime.datetime.fromtimestamp(1519909295.2198606)    #時間戳轉換為日期時間
print(ts)   #2018-03-01 21:01:35.219861

# 日期時間轉時間戳
time. mktime(dt. timetuple())

# 時間計算
datetime.timedelta
( days=0,seconds=0, microseconds=0 milliseconds=0,minutes=0, hours=0, weeks=0 )

3.時間與字串之間轉換

datetime.strptime(string, format_string)
# 例子 將時間格式的字串轉換為時間物件
day = datetime.datetime.strptime('2018-6-1 13:13:13', '%Y-%m-%d %H:%M:%S')
print(type(day), day)

# 將時間物件進行格式化
now = datetime.datetime.now()     
new_day = now.strftime('%Y-%m-%d %H:%M:%S'
) # 注意與time模組的稍有不同 print(type(new_day), new_day) # <class 'str'> 2018-08-25 22:37:35 print(type(now), now) # <class 'datetime.datetime'> 2018-08-25 22:37:35.391563

這裡寫圖片描述

4.時區問題:

必須要在時間物件上附加時區資訊 !

datetime.timezone( offset, name )

時區物件:

tz_utc = datetime.timezone.utc   #標準時區
print('str:',str(tz_utc))   #str: UTC+00:00
print('repr:',repr(tz_utc))   #repr: datetime.timezone.utc
print('------')

tz_china = datetime.timezone(datetime.timedelta(hours=8),'Asia/Beijing')   #北京(+8區)
print('str:',str(tz_china))   #str: Asia/Beijing
print('repr:',repr(tz_china))   #repr: datetime.timezone(datetime.timedelta(0, 28800), 'Asia/Beijing')
print('------')

tz_america = datetime.timezone(datetime.timedelta(hours=-8),'America/los_Angeles')   #美國時區
print('str:',str(tz_america))   #str: America/los_Angelesg
print('repr:',repr(tz_america))   #repr: datetime.timezone(datetime.timedelta(-1, 57600), 'America/los_Angeles')
print('------')

轉換時間:

cn_dt = datetime.datetime(2018,2,27,20,30,tzinfo=tz_china)  #北京時間
print('北京時間:',cn_dt)

utc_dt = cn_dt.astimezone(datetime.timezone.utc)    #0時區
print('零時區時間:str:',str(utc_dt))   #str: 2018-02-27 12:30:00+00:00
print('repr:',repr(utc_dt))  #repr: datetime.datetime(2018, 2, 27, 12, 30, tzinfo=datetime.timezone.utc)
print('------')

us_dt = utc_dt.astimezone(tz_america)           #美國時間
print('美國時間:str:',str(us_dt))   #str: 2018-02-27 04:30:00-08:00
print('repr:',repr(us_dt))  #repr: datetime.datetime(2018, 2, 27, 4, 30, tzinfo=datetime.timezone(datetime.timedelta(-1, 57600), 'America/los_Angeles'))
print('------')