python datetime、date、time、string、timedelta等详解(格式转换)

总结:
datetime转date:
dt.date()
date转datetime:
datetime.combine(date,datetime.min.time())
datetime转string:
dt.strftime(“%Y-%m-%d %H:%M:%S”)
string转datetime:
datetime.strptime(“2022-10-01 12:00:00”,“%Y-%m-%d %H:%M:%S”)
date转string:
d.strftime(“%Y-%m-%d”)
string转date:
不能直接转换
dt=datetime.strptime(“2022-10-01 12:00:00”,“%Y-%m-%d %H:%M:%S”)
dt.date()

全部笔记:
from datetime import datetime, date, time,timedelta
datetime: 2022-10-01 00:00:00.000000
date: 2022-10-01
time: 00:00:00.000000
timedelta 指定时间间隔 与日期进行计算
直接创建datetime、date、time:
datetime(year,month,day,hour,minute,second,microsecond)
date(year,month,day)
time(hour,minute,second,microsecond)
获取当前datetime、date:
today = datetime.now()
today = date.today()
datetime与date、time转换:
dt.date() datetime提取date
dt.time() datetime提取time
datetime.combine(dt.date(),dt.time()) date和time合并成datetime
datetime与时间戳(秒)、ISO公历序数(天)、时间格式字符串转换:
datetime.fromtimestamp(15777777.23434)
datetime.fromordinal(737425)
datetime.fromisoformat(“2022-10-01 02:00:00”) YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]]
date与时间戳、ISO公历序数、时间格式字符串转换:
date.fromtimestamp(15777777)
date.fromordinal(737425)
date.fromisoformat(“2022-10-01”) YYYY-MM-DD
time与字符串转换:
time.fromisoformat(“12:45:10”)
获取datetime、date、time某个参数:
date:year、month、day
time:hour、minute、second、microsecond
datetime:year、month、day、hour、minute、second、microsecond
dt.year
修改datetime、date、time中的参数:
dt.replace(year=2022)
返回datetime、date的时间元祖:
dt.timetuple()
datetime、date返回ISO公历序数:
dt.toordinal()
datetime返回时间戳:
dt.timestamp()
datetime、date返回当前工作日:
dt.weekday() 0代表星期一,6代表星期日
dt.isoweekday() 1代表星期一,7代表星期日
datetime、date返回一个包含目标日期的年份、在一年中的第几周、周几三个元素在内的元组:
dt.isocalendar() (2022, 1, 2)
datetime、date、time返回标准化时间字符串:
dt.isoformat() 默认以字符T分割时间和日期 ‘2022-10-01T15:27:05.882867’
dt.isoformat(sep=” ”) 以空格“ ”分隔日期和时间 ‘2022-10-01 15:27:05.882867’
d.isoformat() 日期部分 ‘2022-10-01’
t.isoformat() 时间部分 ‘15:27:05.882867’
datetime、date、time转字符串:
strftime(“%Y-%m-%d %H:%M:%S”)
字符串转datetime:
datetime.strptime(“2022-10-01 12:00:00”,“%Y-%m-%d %H:%M:%S”)
datetime能同类比较能减法运算能与timedelta运算
date能同类比较能减法运算能与timedelta运算
time只能同类比较

timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)可与datetime、date进行运算,timedelta对象定义后内部仅储存days、seconds、microseconds

原文地址:https://baijiahao.baidu.com/s?id=1666748705793386009&wfr=spider&for=pc

你可能感兴趣的:(Python,python)