Python中时间操作使用还是挺频繁的,主要使用到time
和datetime
这两个库,下面记录常用的时间操作
当前时间戳
1 | import time |
2 | ticks = time.time() |
3 | print(ticks) |
当前时间(now)
1 | import datetime |
2 | now = datetime.datetime.now() |
3 | print(now) |
本地时间(localtime)
1 | import time |
2 | loacltime = time.loacltime() |
格式化时间(strftime)
datetime
1
import datetime
2
now = datetime.datetime.now()
3
strftime = now.strftime('%Y-%m-%d %H:%M:%S')
4
print(strftime)
time
1
import time
2
now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
3
print(now)
时间转时间戳(timestamp)
1 | import datetime |
2 | now = datetime.datetime.now() |
3 | t = now.timestamp() |
4 | print(t) |
时间戳转时间(fromtimestamp)
1 | from datetime import datetime |
2 | import time |
3 | ticks = time.time() |
4 | print(datetime.fromtimestamp(ticks)) |
时间加减(timedelta)
1 | import datetime |
2 | d1 = datetime.datetime.now() |
3 | d2 = d1 + datetime.timedelta(hours = 8) #时间+8小时 |
其中可选参数:天(days), 小时(hours), 分钟(minutes), 秒(seconds), 微秒(microseconds)
开发中的操作
- 返回一周时间列表[‘2019-12-8’, ‘2019-12-9’,…]
1
import datetime
2
today = datetime.date.today()
3
date_list = [(today - datetime.timedelta(days=i)).strftime('%Y-%m-%d') for i in range(7)] #控制天数
4
date_list.reverse()
5
print(date_list)