datetime的操作

from datetime import date, time, datetime, timedelta, tzinfo

1. datetime模塊簡介

  • python中關於時間的格式:

    • 時間對象格式struct_time(struct_time 之間可以加減運算):time模塊中的概念
    • 時間戳timestamp(timestamp之間可以加減運算):time模塊中的概念,時間戳指的是從1970年1月1日00:00:00開始按秒計算的偏移量。爲浮點型,如1583833864.3143494
    • 日期字符串;
    • ctime
    • Gregorian
    • ISO標準
  • datetime模塊有6個類:

    • date類:日期對象,常用屬性有year/month/day
    • time類:時間對象
    • datetime類:日期時間對象,常用屬性hour/minute/second/microsecond
    • datetime_CAPI類:日期時間對象C語言接口
    • timedelta類:時間間隔,即兩個時間點之間的長度
    • tzinfo類:時區信息對象
  • datetime模塊有兩個常用常亮:

    • MAXYEAR:返回能表示的最大年份
    • MINYEAR:返回能表示的最小年份
  • python中時間日期格式化符號(date轉換成字符串有實例代碼):

    • %y:兩位數的年份表示(00-99)
    • %Y:四位數的年份表示(0000-9999)
    • %m:月份(1-12)
    • %d:月內中的一天(0-31)
    • %H:24小時制小時數(0-24)
    • %I:12小時制小時數(01-12)
    • %M:分鐘數(00-59)
    • %S:秒(00-59)
    • %a:本地簡化星期名稱
    • %A:本地完整星期名稱
    • %b:本地簡化月份名稱
    • %B:本地完整月份名稱
    • %c:本地相應的日期表示和時間表示
    • %j:年內的一天(001-366)
    • %p:本地A.M.或P.M.的等價符
    • %U:一年中的星期數(00-53)星期天爲星期的開始
    • %w:星期(0-6),星期天爲星期的開始
    • %W:一年中的星期數(00-53)星期一爲星期的開始
    • %x:本地相應的日期表示
    • %X:本地相應的時間表示
    • %Z:當前時區的名稱
    • %%:%號本身

2. date類

2.1 date對象(類)簡介

  • date對象由year、month、day三部分構成,格式如下:x年-x月-x日。
# 獲取今天的日期
cur = date.today()
print(cur)
print('year:', cur.year, 'month:', cur.month, 'day:', cur.day)
# 也可以通過__getattribute__獲取年月日
print(cur.__getattribute__('year'), cur.__getattribute__('month'), cur.__getattribute__('day'))

# 指定時間
date_ = date(2018, 9, 4)
print(date_)
2020-03-10
year: 2020 month: 3 day: 10
2020 3 10
2018-09-04

2.2 方法1:比較兩個日期的大小

x = date(2017, 10, 3)
y = date(2017, 10, 4)
# x、y兩個日期是否相等
print(x.__eq__(y))
# x日期是否大於等於y日期
print(x.__ge__(y))
# 大於(x>y)
print(x.__gt__(y))
# 小於等於(x<=y)
print(x.__le__(y))
# 小於(x < y)
print(x.__lt__(y))
# 不等於(x!=y)
print(x.__ne__(y))
False
False
False
True
True
True

2.3 獲取兩個日期相差多少天

x = date(2017, 10, 3)
y = date(2017, 10, 4)
print(x.__sub__(y))  # x-y
print(x.__rsub__(y))  # y-x
# 計算結果的返回值類型爲datetime.timedelta, 如果獲得整數類型的結果則按下面的方法操作:
print(x.__sub__(y).days)
print(x.__rsub__(y).days)
-1 day, 0:00:00
1 day, 0:00:00
-1
1

2.4 date日期與各種時間格式轉化

2.4.1 date與字符串相互轉換

2.4.1.1 date轉化成字符串(str類型)

# _format__(**)以指定格式輸出字符串,或者strftime(**)

# __format__
x = date(2019, 8, 8)
print(x.__format__('%Y-%m-%d-%W'), type(x.__format__('%Y-%m-%d-%W'))) 
print(x.__format__('%Y/%m/%d'))
print(x.__format__('%y/%m/%d'))
print(x.__format__('%D'))
print("#############################")

# strftime:括號內爲要轉換成字符串的格式
y = date(2019, 8, 8)
print(y.strftime('%Y%m%d%w'), type(y.strftime('%Y%m%d%w')))
print(y.strftime('%w'))  # 獲得周幾,週日到週六爲0-6
print(y.strftime('%W'))  # 一年中的第幾周,星期一爲一週的開始
print("#################################")

# 如果只是簡單的獲得日期的字符串,可使用__str__()
x = date(2019, 8, 7)
print(x.__str__(), type(x.__str__()))

2019-08-08-31 <class 'str'>
2019/08/08
19/08/08
08/08/19
#############################
201908084 <class 'str'>
4
31
#################################
2019-08-07 <class 'str'>
# python中其他%代表含義示例
# 其中最常用的有%Y, %m, %d, %H, %M, %S, %w, %W
z = date(2020, 1, 2) # 2020年1月2日爲星期四,一年中的第0周(或第1周)
print('兩位數的年份(年份後兩位):', z.strftime('%y'))
print('四位數的年份:', z.strftime('%Y'))
print('月份(1-12):', z.strftime('%m'))
print('一月中的一天(1-31):', z.strftime('%d'))
print('24小時制小時數(0-24):', z.strftime('%H'))
print('12小時制小時數(01-12):', z.strftime('%I'))
print('分鐘數(0-59):', z.strftime('%M'))
print('秒(00-59):', z.strftime('%S'))
print('英文星期簡稱:', z.strftime('%a'))
print('英文完整日期名稱:', z.strftime('%A'))
print('英文月份簡稱:', z.strftime('%b'))
print('英文月份全稱:', z.strftime('%B'))
print('ctime日期時間表示:', z.strftime('%c'))
print('年內的一天(001-366):', z.strftime('%j'))
print('A.M(上午)或P.M(下午)', z.strftime('%p'))
print('一年中星期數(00-53),星期天爲一週的開始:', z.strftime('%U'))
print('星期幾(0-6),星期天爲星期開始:', z.strftime('%w'))
print('一年中的星期數(00-53), 星期一爲星期的開始:', z.strftime('%W'))
print('月/日/兩位數年:', z.strftime('%x'))
print('時:分:秒---', z.strftime('%X'))
print('當前時區的名稱:', z.strftime('%Z'))
兩位數的年份(年份後兩位): 20
四位數的年份: 2020
月份(1-12): 01
一月中的一天(1-31): 02
24小時制小時數(0-24): 00
12小時制小時數(01-12): 12
分鐘數(0-59): 00
秒(00-59): 00
英文星期簡稱: Thu
英文完整日期名稱: Thursday
英文月份簡稱: Jan
英文月份全稱: January
ctime日期時間表示: Thu Jan  2 00:00:00 2020
年內的一天(001-366): 002
A.M(上午)或P.M(下午) AM
一年中星期數(00-53),星期天爲一週的開始: 00
星期幾(0-6),星期天爲星期開始: 4
一年中的星期數(00-53), 星期一爲星期的開始: 00
月/日/兩位數年: 01/02/20
時:分:秒--- 00:00:00
當前時區的名稱: 

2.4.1.2 字符串轉化成date

暫無,得知後補充

2.4.2 date與struct_time相互轉換

2.4.2.1 date轉化成struct_time(time.struct_time類型)

import time
a = time.localtime()  # localtime是 把從1970-1-1零點零分到當前時間系統所偏移的秒數時間轉換爲本地時間,故可選參數爲偏移的秒數
b = time.gmtime()  # gmtime函數轉換後的時間沒有經過時區變換,是UTC時間,localtime比uct時間(即世界標準時間)慢8個小時
print(a, '####', type(a))
print(b, '####', type(b))
time.struct_time(tm_year=2020, tm_mon=3, tm_mday=10, tm_hour=17, tm_min=21, tm_sec=36, tm_wday=1, tm_yday=70, tm_isdst=0) #### <class 'time.struct_time'>
time.struct_time(tm_year=2020, tm_mon=3, tm_mday=10, tm_hour=9, tm_min=21, tm_sec=36, tm_wday=1, tm_yday=70, tm_isdst=0) #### <class 'time.struct_time'>
# timetuple():類型爲time.struct_time的數組,但有關時間的部分元素值爲0
# 該方法爲了兼容time.localtime(),此處的time是time模塊,非datetime下的time類
x = date(2019, 3, 24)
print(x.timetuple())
print(x.timetuple().tm_year)
print(x.timetuple()[0])
# tm_wday:星期幾(週一0,週日6)
# tm_yday:一年中的第幾天
time.struct_time(tm_year=2019, tm_mon=3, tm_mday=24, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=83, tm_isdst=-1)
2019
2019

2.4.2.2 struct_time轉化成date

暫無,得知後補充

2.4.3 date與時間戳相互轉換

2.4.3.1 date轉化成時間戳(float類型)

暫無,得知後補充

2.4.3.2 時間戳轉化成date

# fromtimestamp():根據給定的時間戮,返回一個date對象
import time
print('time時間戳:', time.time(), type(time.time()))
print(date.fromtimestamp(time.time()))
time時間戳: 1583833864.3143494 <class 'float'>
2020-03-10

2.4.4 date與ctime相互轉換

2.4.4.1 將date轉換成ctime(str類型)

# ctime格式
import time
time.ctime(3) # 可選參數爲1970-1-1零點零分偏移的秒數,即時間戳的秒數
'Thu Jan  1 08:00:03 1970'
x = date(2019, 3, 24)
print(x.ctime(), type(x.ctime()))
Sun Mar 24 00:00:00 2019 <class 'str'>

2.4.4.2 將ctime轉換成date

暫無,得知後補充

2.4.5 date與Gregorian日曆時間格式相互轉換

2.4.5.1 date轉換成Gregorian(int類型)

# fromordinal():將Gregorian日曆時間轉換爲date對象;Gregorian Calendar :一種日曆表示方法,類似於我國的農曆,西方國家使用比較多。
x = date(2019, 3, 4)
y = x.toordinal()  # y是Gregorian表示的日期
print(y, type(y))
737122 <class 'int'>

2.4.5.2 Gregorian轉換成date

x = date(2019, 3, 4)
y = x.toordinal()  # y是Gregorian表示的日期,表示公元公曆開始到現在的天數。公元1年1月1日爲1
print(y)
print(date.fromordinal(y))
print(date.fromordinal(737122))
737122
2019-03-04
2019-03-04

2.4.6 將date轉換成ISO標準格式

# 如果想要讓所使用的日期符合ISO標準,有如下三個方法:

# 方法1:isocalendar():返回包含三個數值的元組
x = date(2020, 1, 1)
print(x.isocalendar())
print(x.isocalendar()[0]) # 日期x的年份
print(x.isocalendar()[1]) # 日期x一年中所在的週數
print(x.isocalendar()[2]) # 日期x是一週的星期幾:週一到週日依次爲1-7
(2020, 1, 3)
2020
1
3
# 方法2:isoformat(),返回ISO 8601標準的日期字符串('YYYY-MM-DD')
x = date(2018, 4, 22)
print(x, type(x))
y = x.isoformat()
print(y, type(y))
2018-04-22 <class 'datetime.date'>
2018-04-22 <class 'str'>
# 方法3:isoweekday(): 返回符合ISO標準的指定日期所在的星期數(週一爲1…週日爲7) 
x = date(2020, 1, 1)
print(x.isoweekday())
# weekday()與isoweekday()相似,只不過是weekday()方法返回的週一爲 0, 週日爲 6
x = date(2020, 1, 1)
print(x.weekday())
3
2

2.4.7 總結

在這裏插入圖片描述

2.6 其他方法及屬性

# replace():替換操作
x = date(2019, 7, 3)
y = x.replace(2020, 2, 29)  # 三個參數依次爲year、month、day
print(x, type(x))
print(y, type(y))
2019-07-03 <class 'datetime.date'>
2020-02-29 <class 'datetime.date'>
# 減操作,不支持加操作
x = date(2019, 7, 3)
y = x.replace(2020, 2, 29)
print(x - y)
-241 days, 0:00:00
# today():返回當前日期
print(date.today())
2020-03-10
# 屬性:max:date類能表示的最大的年、月、日的數值
# 屬性:min:date類能表示的最小的年、月、日的數值
# 屬性:resolution:最小時間間隔
print(date.max)
print(date.min)
print(date.resolution)
9999-12-31
0001-01-01
1 day, 0:00:00

3. time類

3.1 time對象(類)簡介

  • time類由hour小時、minute分鐘、second秒、microsecond毫秒和tzinfo五部分組成(tzinfo爲時區)

  • time所有的方法和屬性date也有

from datetime import time
t = time(10, 15, 32, 1000)
print(t, type(t))
print(t.hour)
print(t.minute)
print(t.second)
print(t.microsecond)

# 與date類相似,也有__getattribute__()方法
print(t.__getattribute__('hour'))
10:15:32.001000 <class 'datetime.time'>
10
15
32
1000
10

3.2 方法1:比較兩個時間的大小(與date相同)

  • 與date類相似,也有__eq__(), __ge__(), __gt__(), __le__(), __lt__(), __ne__()

3.3 方法2:將時間轉化成字符串(與date相同)

# __format__
x = time(10, 15, 55, 1000)
print(x.__format__('%H:%M:%S'))

# strftime
print(x.strftime('%H'))

# __str__()簡單字符串
print(x.__str__())
10:15:55
10
10:15:55.001000

3.4 方法3:time轉化成ISO標準(與date大致相同,比date方法少)

x = time(12,20,59,899)
y = x.isoformat()
print(y, type(y))
# time沒有isocalendar
12:20:59.000899 <class 'str'>

3.5 其他方法和屬性(與date相同)

# max/min/resolution(最小時間間隔)
print(time.max)
print(time.min)
print(time.resolution)
x = time(12,20,59,899)
y = time(12,20,59,898)
# time不支持加減操作
23:59:59.999999
00:00:00
0:00:00.000001

4. datetime

4.1 datetime對象(類)簡介

datetime結合了date(日期)和time(時間),有year, month, day, hour, minute, second, microsecond, tzinfo構成。
其中有關時間的部分是可選的

p1 = datetime(2020, 1, 2, 10, 15, 32, 1000)
p2 = datetime(2020, 1, 2)
print(p1, type(p1))
print(p2, type(p2))
print(p1.year)
print(p1.minute)


# 與date類相似,也有__getattribute__()方法
print(p1.__getattribute__('hour'))
2020-01-02 10:15:32.001000 <class 'datetime.datetime'>
2020-01-02 00:00:00 <class 'datetime.datetime'>
2020
15
10

4.2 與date類對比

  • datetime具有上述date所有的方法和屬性(time所有的方法屬性,date同樣也有)
p1 = datetime(2020, 1, 2, 10, 15, 32, 1000)
p2 = datetime(2020, 1, 2)
# x、y兩個日期是否相等
print(p1.__eq__(p2))
# x日期是否大於等於y日期
print(p1.__ge__(p2))
# 大於(x>y)
print(p1.__gt__(p2))
# 小於等於(x<=y)
print(p1.__le__(p2))
# 小於(x < y)
print(p1.__lt__(p2))
# 不等於(x!=y)
print(p1.__ne__(p2))
False
True
True
False
False
True
p1 = datetime(2020, 1, 2, 10, 15, 32, 1000)
p2 = datetime(2020, 1, 2)
print(p1.__sub__(p2).days)
print(p1.__rsub__(p2).days)
0
-1
x = datetime(2019, 12, 1, 13, 1, 3)
print(x.__format__('%H'))
print(x.strftime("%H"))
print(x.__str__())
13
13
2019-12-01 13:01:03
x = datetime(2019, 12, 1, 13, 1, 3)
print(x.timetuple())
print(x.timetuple().tm_year)
print(x.timetuple()[0])
time.struct_time(tm_year=2019, tm_mon=12, tm_mday=1, tm_hour=13, tm_min=1, tm_sec=3, tm_wday=6, tm_yday=335, tm_isdst=-1)
2019
2019
import time
print(datetime.fromtimestamp(time.time()))
2020-03-10 22:24:51.923358
x = datetime(2019, 12, 1, 13, 1, 3)
print(x.ctime(), type(x.ctime()))
Sun Dec  1 13:01:03 2019 <class 'str'>
x = datetime(2019, 12, 1, 13, 1, 3)
y = x.toordinal()
print(y)
print(datetime.fromordinal(y))
737394
2019-12-01 00:00:00
x = datetime(2019, 12, 1, 13, 1, 3)
print(x.isocalendar())
print(x.isocalendar()[0]) # 日期x的年份
print(x.isocalendar()[1]) # 日期x一年中所在的週數
print(x.isocalendar()[2])
(2019, 48, 7)
2019
48
7
x = datetime(2019, 12, 1, 13, 1, 3)
print(x, type(x))
y = x.isoformat()
print(y, type(y))
2019-12-01 13:01:03 <class 'datetime.datetime'>
2019-12-01T13:01:03 <class 'str'>
# 方法3:isoweekday(): 返回符合ISO標準的指定日期所在的星期數(週一爲1…週日爲7) 
x = datetime(2020, 1, 1)
print(x.isoweekday())
# weekday()與isoweekday()相似,只不過是weekday()方法返回的週一爲 0, 週日爲 6
x = datetime(2020, 1, 1)
print(x.weekday())
3
2
x = datetime(2019, 12, 1, 13, 1, 3)
print(x.replace(2020, 2, 29))
2020-02-29 13:01:03
print(datetime.today())
x = datetime(2020, 3, 28, 15, 0, 0 , 0)
y = datetime(2020, 3, 13, 12, 0, 0, 0)
print(x - y)
2020-03-11 10:08:33.473686
15 days, 3:00:00
print(datetime.max)
print(datetime.min)
print(datetime.resolution)
9999-12-31 23:59:59.999999
0001-01-01 00:00:00
0:00:00.000001

4.3 datetime獨有的方法和屬性

# now/date/time/utctimetuple/utcnow/combine/utcfromtimestamp
import time
a = datetime.now()
print('a:', a)
print('date:',a.date())
print('time:',a.time())  # 獲取year爲屬性:a.year
print('utctimetuple:',a.utctimetuple())  # 變換後的UTC時間元組,tm_hour爲當前電腦時間
print('utcnow:',datetime.utcnow()) # 返回當前UTC時間,比當前電腦時間慢8小時
print('utcfromtimestamp',datetime.utcfromtimestamp(time.time()))  # 將時間戳轉化爲UTC時間組
print('combine',datetime.combine(a.date(),a.time()))  # 將date與time合併在一起
print('strptime',datetime.strptime('2020-1-2 12:20','%Y-%m-%d %H:%M'))  # 根據string, format 2個參數,返回一個對應的datetime對象
print(a.timestamp()) # 將datetime轉換成時間戳
a: 2020-03-11 11:20:17.261216
date: 2020-03-11
time: 11:20:17.261216
utctimetuple: time.struct_time(tm_year=2020, tm_mon=3, tm_mday=11, tm_hour=11, tm_min=20, tm_sec=17, tm_wday=2, tm_yday=71, tm_isdst=0)
utcnow: 2020-03-11 03:20:17.261216
utcfromtimestamp 2020-03-11 03:20:17.261216
combine 2020-03-11 11:20:17.261216
strptime 2020-01-02 12:20:00
1583896817.261216

4.4 總結

在這裏插入圖片描述

5. timedelta

5.1 datetime對象(類)簡介

timedelta表示一個時間長度,即兩個datetime之間的差值

a = datetime(2020, 3, 28, 15, 0, 0 , 0)
b = datetime(2020, 3, 13, 12, 0, 0, 0)
print(a - b)
15 days, 3:00:00
a = datetime(2020, 3, 20, 15, 0, 0 , 0)
# 上述a、b只能進行減操作,不能進行加操作
print(a + timedelta(3)) # 後三天
print(a + timedelta(-3)) # 前三天
# class datetime.timedelta(days=0,seconds=0,microseconds=0,milliseconds=0,minutes=0,hours=0,weeks=0)
# 所有參數均可選,但python內部只存儲了days,seconds和microseconds三種單位,故其他參數會轉換成這三種單位
# 1 millisecond = 1000 microseconds
print(a + timedelta(3, 1, 2, 4, 5, 6, 8))
2020-03-23 15:00:00
2020-03-17 15:00:00
2020-05-18 21:05:01.004002

6. 關於時間計算的操作

6.1 獲取當前時間

print(date.today()) # 只有日期,沒有時間
print("###########")

print(datetime.now())
print(datetime.now().date())
print(datetime.now().time())
print(datetime.now().year)
print("############")

print(datetime.today())
print(datetime.today().date())
print(datetime.today().time())
print(datetime.today().year)
2020-03-11
###########
2020-03-11 10:47:59.627967
2020-03-11
10:47:59.627967
2020
############
2020-03-11 10:47:59.628966
2020-03-11
10:47:59.628966
2020

6.2 計算時間差

a = datetime(2020, 3, 28, 15, 0, 0 , 0)
b = datetime(2020, 3, 13, 12, 0, 0, 0)
diff = a - b
print(diff)
print(diff.days)
print(diff.seconds)
# diff 只有days和seconds兩個屬性
15 days, 3:00:00
15
10800

6.3 有關delta的用法

delta是兩個datetime的時間差,可以靈活使用delta計算指定日期前幾天、上個月最後一天、當月第一天、前一週等等

7. tzinfo詳解

# tzinfo是關於時區信息的類
# tzinfo是一個抽象類,所以不能直接被實例化,具體如下:

class UTC(tzinfo):
    """UTC"""
    def __init__(self,offset = 0):
        self._offset = offset

    def utcoffset(self, dt):
        return timedelta(hours=self._offset)

    def tzname(self, dt):
        return "UTC +%s" % self._offset

    def dst(self, dt):
        return timedelta(hours=self._offset)
#北京時間
beijing = datetime(2020, 1, 1, 0, 0, 0,tzinfo = UTC(8))
print(beijing)

#曼谷時間
bangkok = datetime(2020, 1, 1, 0, 0, 0,tzinfo = UTC(7))
print(bangkok)

#北京時間轉成曼谷時間
print(beijing.astimezone(UTC(7)))

#計算時間差時也會考慮時區的問題
timespan = beijing - bangkok
print(timespan)
2020-01-01 00:00:00+08:00
2020-01-01 00:00:00+07:00
2019-12-31 23:00:00+07:00
-1 day, 23:00:00

8. 特殊實例講解(日期類似Gregorian)

  • 背景:讀取一份excel,其中某一列日期爲2019.09.30,但是使用pd.read_excel讀取後,日期顯示43738,該int日期看似是Gregorian,但實際使用fromordinal轉換成datetime後並不是想要的2019.09.30結果。
    在這裏插入圖片描述
dates = 43738
today = datetime.strptime('1899-12-30','%Y-%m-%d') + timedelta(days=dates)
print(today, type(today))
# 可以看到這是想要的結果,類型爲datetime
2019-09-30 00:00:00 <class 'datetime.datetime'>

9. time模塊簡介

  • time模塊一與datetime有很多相似之處,也有strftime,fromordinal,mktime等等,其概念與datetime也大致相同,在這裏不贅述。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章