from datetime import datetime
# 将字符串转换为datetime对象
date_string = "2023-10-05 14:30:00"
date_object = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print("字符串转datetime:", date_object)
# 将datetime对象转换为字符串
formatted_date = date_object.strftime("%Y-%m-%d %H:%M:%S")
print("datetime转字符串:", formatted_date)
# 获取当前时间并格式化
current_time = datetime.now()
formatted_current_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
print("当前时间:", formatted_current_time)
# 时间戳转换为datetime对象
timestamp = 1696513800
date_from_timestamp = datetime.fromtimestamp(timestamp)
print("时间戳转datetime:", date_from_timestamp)
# datetime对象转换为时间戳
timestamp_from_date = date_object.timestamp()
print("datetime转时间戳:", timestamp_from_date)
strptime 方法将字符串格式的时间转换为 datetime 对象。需要指定字符串的格式。strftime 方法将 datetime 对象转换为指定格式的字符串。datetime.now() 获取当前时间,并通过 strftime 格式化输出。fromtimestamp 方法将时间戳(秒数)转换为 datetime 对象。timestamp 方法将 datetime 对象转换为时间戳(秒数)。上一篇:python list 查找
下一篇:python常用算法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站