Python中关于日期和时间处理的常用方法

转换为 2023-12-29 10:57:34

import time

# 获得当前时间时间戳
now = int(time.time())
# 转换为其他日期格式,如:"%Y-%m-%d %H:%M:%S"
timeArray = time.localtime(now)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(otherStyleTime)

转换为 2023-12-29

import time

# 获得当前时间时间戳
now = int(time.time())
# 转换为其他日期格式,如:"%Y-%m-%d %H:%M:%S"
timeArray = time.localtime(now)
otherStyleTime = time.strftime("%Y-%m-%d", timeArray)
print(otherStyleTime)

封装为方法:

import time


def now_str():
    # 获得当前时间时间戳
    now = int(time.time())
    # 转换为其他日期格式,如:"%Y-%m-%d %H:%M:%S"
    time_obj = time.localtime(now)
    return time.strftime("%Y-%m-%d", time_obj)


print(now_str())

你可能感兴趣的:(python,python,日期和时间)