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)