1. 程式人生 > 其它 >時間模組總結

時間模組總結

time

# 1、時間戳 型別:浮點數
>>> time.time()
1625208594.7282684

# 2、時間字串
>>> time.strftime("%Y-%m-%d %X")
'2021-07-02 15:38:17'
>>> time.strftime("%Y-%m-%d %H-%M-%S")
'2021-07-02 15-39-30'

datetime

# 1、datetime.datetime.now() 是一個datetime型別,使用時可以強制轉化為字串
>>> str(datetime.datetime.now())[0:19]
'2021-07-02 15:44:51'
>>> datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S")
'2021-07-02 15-47-49'

datetime的加減運算

# 獲取當前日期將來或過去的n天
def get_date_others(n):
    return str(datetime.date.today() + datetime.timedelta(days=n))

# 獲取當前日期將來或過去的n天 的零點
def get_date_time_others_zero(n):
    now = datetime.datetime.now()
    zero = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second,
           microseconds=now.microsecond) + datetime.timedelta(days=n)
    
# 獲取當前日期將來或過去的n天 的24點 
def get_date_time_others_last(n):
    now = datetime.datetime.now()
    last = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second,
           microseconds=now.microsecond) + datetime.timedelta(days=n, hours=23, minutes=59, seconds=59)