python data转为datetime,datatime转为date,date转为str,datetime转为str

一下为python实现date,datetime,str互转
date 日期到天
datetime 时间到毫秒
str 日期和时间格式化字符串

  • 导入库
#导入库
from datetime import datetime, date

# 获取datetime
now = datetime.now()
print('获取datetime:',now)

# 获取date
today = date.today()
print('获取date:',today)
  • date转datetime
# date 转 datetime
print('date 转 datetime:',datetime.combine(today, datetime.min.time()))
  • datetime转date
# datetime转date
print('datetime转date:',now.date())
  • datetime转str
# datetime转str
print('datetime转str:',now.strftime('%Y-%m-%d'))
  • date转datetime
# date 转 datetime
print('date 转 datetime:',datetime.combine(today, datetime.min.time()))
  • date转str
# date转str
print('date转str:',today .strftime('%Y-%m-%d'))
  • 完整示例
from datetime import datetime, date

# 获取datetime
now = datetime.now()
print('获取datetime:',now)

# datetime转date
print('datetime转date:',now.date())

# datetime转str
print('datetime转str:',now.strftime('%Y-%m-%d'))

# 获取date
today = date.today()
print('获取date:',today)

# date 转 datetime
print('date 转 datetime:',datetime.combine(today, datetime.min.time()))

# date转str
print('date转str:',today .strftime('%Y-%m-%d'))

你可能感兴趣的:(程序设计基础)