python中時間處理小結

python中時間處理

總結一下python中的常用時間處理相關的模塊的使用. 主要是 time datetime 兩個模塊.

time

比較底層的時間處理相關模塊. 記錄常用的時間操作方法

  1. time.time()
    獲取當前時間戳(單位是, 和一般的JAVA默認毫秒時間戳單位不同)
time.time()
1611794576.614294
  1. time.localtime([seconds])
    將時間戳轉換爲time.struct_time 類型本地時間, 如果不給定參數, 使用當前時間的時間戳.
localtime(...)
    localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
                              tm_sec,tm_wday,tm_yday,tm_isdst)
    
    Convert seconds since the Epoch to a time tuple expressing local time.
    When 'seconds' is not passed in, convert the current time instead.

struct_time 可以看成同一時間戳不同時區的不同表達, 這個值會因爲時區不同而不同.

  1. time.strftime()
strftime(format[, tuple]) -> string
    
    Convert a time tuple to a string according to a format specification.
    See the library reference manual for formatting codes. When the time tuple
    is not present, current time as returned by localtime() is used.

格式化時間, 注意此處的第二個參數是tuple, 實際使用的時候傳遞的是struct_time. 如果第二個參數不賦值, 那麼以time.localtime() 作爲默認值, 即是以某種格式, 格式化本地時間

比如格式化當前時間

time.strftime('%Y-%m-%d %H:%M:%S')
'2021-01-28 08:57:20'
  1. time.strptime
    將一個時間的字符串形式轉換成時間元祖 time.struct_time
strptime(string, format) -> struct_time
    
    Parse a string to a time tuple according to a format specification.
    See the library reference manual for formatting codes (same as
    strftime()).
time.strptime('2020-02-03', '%Y-%m-%d')
time.struct_time(tm_year=2020, tm_mon=2, tm_mday=3, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=34, tm_isdst=-1)
  1. time.mktime

將時間元祖(time.struct_time)轉換爲時間戳, 和 time.localtime() 相反

mktime(tuple) -> floating point number
    
    Convert a time tuple in local time to seconds since the Epoch.
    Note that mktime(gmtime(0)) will not generally return zero for most
    time zones; instead the returned value will either be equal to that
    of the timezone or altzone attributes on the time module.
time.mktime(time.localtime())
1611796088.0
  1. time.sleep(seconds)
sleep(seconds)
    
    Delay execution for a given number of seconds.  The argument may be
    a floating point number for subsecond precision.

線程休眠時間

time模塊裏面的時間操作比較底層, 涉及到一個結構time.struct_time 時間元祖. 格式化以及反向操作, 都是以時間元祖(time.struct_time) 爲基礎進行的. 總體完成在時間格式化字符串, 時間戳以及時間元祖之間的轉換操作. 如下的轉換關係:

時間格式字符串 <--strptime/strftime--> struct_time(結構化時間表達, 跟時區有關) <--localtime/mktime--> timestamp(時間戳, 單位秒)

常用功能 time.sleep([sec]) 線程休眠
以及計算程序執行時間

start_time = time.now()
......
duration = time.now() - start_time

datetime

datetime 是一個模塊, 相比於time模塊具有更多高級的功能相比於time中只有struct_time這種結構化時間類型. datetime 模塊中有更多的表示時間的類,其中有4類比較重要, 一個是同名的datetime 一個是 timedelta, 一個是 time, 一個是date. 實際在使用import 的時候 因爲 datetime類和模塊同名了, 所以其實最好是 import datetime 而不是 from datetime import datetime 這種導入, 前者可操作的類型更多一些.

datetime.date: 只需要傳遞年月日, 表徵的是日期

date(year, month, day) --> date object
datetime.date(2020,2,1)
datetime.date(2020, 2, 1)

datetime.time: 只需要傳遞時分秒毫秒時區信息, 表徵的是24小時時間.

time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object
datetime.time(18,2,2)
datetime.time(18, 2, 2)

datetime.datetime: 上面兩者的結合, 表徵日期和時間

datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
 |  
 |  The year, month and day arguments are required. tzinfo may be None, or an
 |  instance of a tzinfo subclass. The remaining arguments may be ints.
datetime.datetime(2020,2,2,20,18,11)
datetime.datetime(2020, 2, 2, 20, 18, 11)

datetime.timedelta: 時間間隔對象, 天,時,分,秒,毫秒,微秒的差值對象. 可根據當前時間和給定日期時間差值計算新的日期時間.

Difference between two datetime values.
 |  
 |  timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
 |  

a = datetime.datetime.now()
print(a)
print(a + datetime.timedelta(days=1))
2021-01-28 09:51:00.202448
2021-01-29 09:51:00.202448

主要操作:

  1. 時間日期類型格式化 以及 字符串轉換成時間.

從時間日期類型到字符串 三個類型都有 strftime這個函數

datetime.date.today().strftime('%Y-%m-%d')
datetime.time(8,20,20).strftime('%H:%m:%S')
datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-28'
'08:01:20'
'2021-01-28 10:06:06'

反過來從字符串到日期時間對象, 只有 datetime.strptime 可以實現, 其他類型 date 和 time 沒有這個函數

datetime.datetime.strptime('2020-02-28 10:06:08', '%Y-%m-%d %H:%M:%S')
datetime.datetime(2020, 2, 28, 10, 6, 8)
  1. 日期時間對象到時間戳

datetime 有 timestamp函數 直接轉換到時間戳

datetime.datetime.now().timestamp()
1611799911.872106

date: 沒有這個函數 只能通過timetuple 函數轉換成time.struct_time 再通過time.mktime() 實現轉換成時間戳.

t = datetime.date(2021,1,28)
time.mktime(t.timetuple())
1611763200.0

但是從字符串到時間 date和 datetime 都提供了 fromtimestamp 方法完成時間戳到日期時間類型轉換.

datetime.datetime.fromtimestamp(datetime.datetime.now().timestamp())
datetime.date.fromtimestamp(datetime.datetime.now().timestamp())
datetime.datetime(2021, 1, 28, 10, 17, 0, 298880)
datetime.date(2021, 1, 28)

總之: datetime模塊包含了較多的時間日期的結構化類型, 在time模塊上提供了更簡潔強大的api完成時間日期的操作.

小結

需要較低層較簡單的時間操作(比如計算程序運行時間)time模塊就夠了, 但是如果要更高級的日期操作, 需要使用datetime模塊.

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