- 已编辑
from datetime import datetime
def timestamp_to_date(timestamp):
date = datetime.fromtimestamp(timestamp)
return date
# 测试示例
timestamp = 1635125400
date = timestamp_to_date(timestamp)
print(date)
from datetime import datetime
def timestamp_to_date(timestamp):
date = datetime.fromtimestamp(timestamp)
return date
# 测试示例
timestamp = 1635125400
date = timestamp_to_date(timestamp)
print(date)
写一个将时间戳格式化成标准的日期格式,传入参数1,转成年月日时间的格式,传入参数2,转成年月日不带时间的格式。
import datetime
def format_timestamp(timestamp, format_type):
# 将时间戳转换为datetime对象
dt = datetime.datetime.fromtimestamp(timestamp)
if format_type == 1:
# 转换为带时间的格式(年-月-日 时:分:秒)
formatted_datetime = dt.strftime('%Y-%m-%d %H:%M:%S')
elif format_type == 2:
# 转换为不带时间的格式(年-月-日)
formatted_datetime = dt.strftime('%Y-%m-%d')
else:
# 参数错误,返回空字符串
formatted_datetime = ''
return formatted_datetime
# 测试示例
timestamp = 1637229862 # 时间戳
format_type1 = 1 # 带时间的格式
format_type2 = 2 # 不带时间的格式
formatted_datetime1 = format_timestamp(timestamp, format_type1)
formatted_datetime2 = format_timestamp(timestamp, format_type2)
print("带时间的格式:", formatted_datetime1)
print("不带时间的格式:", formatted_datetime2)