Python Datetime 时间函数

Python Datetime

Posted by BlueFat on Friday, August 12, 2022
import datetime
datestr ='2021-06-10 15:16:08'
dt = datetime.datetime.strptime(datestr, '%Y-%m-%d %H:%M:%S')
print(type(dt), dt)
print(dt.strftime( '%/%m/%d-%H:%M:%S')) # 输出为字符串
print("{:%Y/%m/%d %H:%M:%S}" . format(dt))  # 输出为字符串

<class 'datetime.datetime'> 2021-06-10 15:16:08
/06/10-15:16:08
2021/06/10 15:16:08
import datetime

d1=datetime.datetime.now() #无时区时间
print(d1)

d2=datetime.datetime.utcnow() #UTC时间
print(d2)

d3=datetime.datetime(2018,8,8,10,5,39)
print(d3)

2022-08-12 14:29:35.393445
2022-08-12 06:29:35.393494
2018-08-08 10:05:39

时区

# timezone 时区类,timedelta 时间差类
print(datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8))))

时间戳

stamp=datetime.datetime.now().timestamp()
print(stamp)
1660285932.433864

d4=datetime.datetime.fromtimestamp(stamp)
print(d4)
2022-08-12 14:32:12.433864

strftime 格式化

日期与格式化

  • 类方法strptime(date_ string, format),返回datetime对象(时间字符串+格式化字符串=>时间对象)
  • 对象方法strftime(format),返回字符串(时间对象通过格式字符串=>时间字符串)
  • 字符串format函数格式化 (时间对象通过格式字符串=>时间字符串)
# datetime类 可以自定义格式!!
d4=datetime.datetime.now()
d5=d4.strftime('%Y-%m-%d!!%H:%M:%S')
print(type(d4),d5)
<class 'datetime.datetime'> 2022-08-12!!14:52:03
# 字符时间解析(不是datetime类) 注意格式如=
d6='2022-08-12=13:52:08'
d7=datetime.datetime.strptime(d6,'%Y-%m-%d=%H:%M:%S')
print(type(d6),d7)
<class 'str'> 2022-08-12 13:52:08

内置调用

d6=datetime.datetime.now()
print(d6,d6.year,d6.month,d6.day, d6.hour)
print(d6.date(),d6.time())
print(d6.weekday())

2022-08-12 14:54:29.202771 2022 8 12 14
2022-08-12 14:54:29.202771
4

timedelta

  • datetime2 = datetime1 + timedelta
  • datetime2 = datetime1 - timedelta
  • timedelta = datetime1 - datetime2
  • 构造方法
    • datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0,hours=0, weeks=0)
    • year = datetime.timedelta(days=365)
  • timedelt对象有方法total_seconds(),返回时间差总秒数

计算

d4=datetime.datetime.now()
print(d4+datetime.timedelta(1,10,hours=8))
print(d4-datetime.timedelta(1))
2022-08-13 22:57:56.545998
2022-08-11 14:57:46.545998

total_seconds()

start=datetime.datetime.now()
time.sleep(3)
end=datetime.datetime.now()

diff=(end-start).
print(diff)
3.004819

time模块

  • time.sleep(secs) 将调用线程挂起指定的秒数

format格式化

d4=datetime.datetime.now()
print("{:%Y/%m/%d %H:%M:%S}".format(d4))
2022/08/12 14:55:54