Python 日期模組 -- datetime
阿新 • • 發佈:2019-02-01
– Start
import time as xtime from datetime import datetime, date, time, timezone, timedelta china_tz = timezone(timedelta(hours=8), 'Asia/Shanghai') # 構造 datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0) dt = datetime(2018, 9, 22, 16, 28, 22) dt = datetime.today() # 無時區資訊 dt = datetime.now() # 無時區資訊 dt = datetime.now(china_tz) # 有時區 dt = datetime.utcnow() # UTC 時區 dt = datetime.combine(date.today(), time(16, 28, 22)) dt = datetime.combine(date.today(), time(16, 28, 22), china_tz) dt = datetime.fromordinal(736959) # datetime.min以來的天數 dt = datetime.fromisoformat('2018-09-22') dt = datetime.fromisoformat('2018-09-22 16:28:22') dt = datetime.fromisoformat('2018-09-22 16:28:22.666') dt = datetime.fromisoformat('2018-09-22 16:28:22.666+08:00') dt = datetime.strptime('2018-09-22 16:28:22', '%Y-%m-%d %H:%M:%S') dt = datetime.fromtimestamp(xtime.time()) dt = datetime.utcfromtimestamp(xtime.time()) # 類屬性 print('----------------------------- 類屬性') print(datetime.min) # 0001-01-01 00:00:00 print(datetime.max) # 9999-12-31 23:59:59.999999 print(datetime.resolution) # 0:00:00.000001 # 例項屬性 print('----------------------------- 例項屬性') dt = datetime(2018, 9, 22, 16, 28, 22, 999, china_tz) print(dt.year) # 2018 print(dt.month) # 9 print(dt.day) # 22 print(dt.hour) # 16 print(dt.minute) # 28 print(dt.second) # 22 print(dt.microsecond) # 999 print(dt.tzinfo) # Asia/Shanghai print(dt.fold) # 0 # 方法 print('----------------------------- 方法') print(dt.date()) # 2018-09-22 print(dt.time()) # 16:28:22.000999 print(dt.timetz()) # 16:28:22.000999+08:00 print(dt.toordinal()) # 736959 print(dt.timestamp()) # 1537604902.000999 print(dt.weekday()) # Monday is 0 and Sunday is 6 print(dt.isoweekday()) # Monday is 1 and Sunday is 7 print(dt.isoformat()) # 2018-09-22T16:28:22.000999+08:00 print(dt.ctime()) # Sat Sep 22 16:28:22 2018 print(dt.strftime('%Y-%m-%d %H:%M:%S')) # 2018-09-22 16:28:22 print(dt.tzname()) # 時區名 print(dt.utcoffset()) # 相對 UTC 時差 print(dt.dst()) # 轉換為夏令時 print(dt.timetuple()) # 轉成 time.struct_time print(dt.utctimetuple()) # 轉成 time.struct_time print(dt.astimezone(timezone.utc)) # 時區轉換 # datetime 是不可變的,replace 不會修改原 datetime today = datetime.today() tomorrow = today.replace(day=today.day + 1) print(tomorrow) year, week, weekday = dt.isocalendar() print(year, week, weekday) # (2018, 38, 6) # 比較時間 dt1 = datetime(2018, 9, 22, 16, 28, 22) dt2 = datetime(2018, 9, 22, 16, 28, 23) if dt1 < dt2: print(f'{dt1} is before {dt2}')
– 更多參見:
– 聲 明:轉載請註明出處
– Last Updated on 2018-09-22
– Written by ShangBo on 2018-09-22
– End