1.定时任务
import datetime
def run_task():
print '0000'
# 三分钟运行一次的定时任务
def timeRun(sched_timer):
flag = 0
while True:
now = datetime.datetime.now()
f_time = now.strftime('%Y-%m-%d %H:%M')
if flag == 0:
if f_time == sched_timer:
run_task()
flag = 1
else:
if flag == 1:
sched_mid_timer = now + datetime.timedelta(minutes=3)
sched_timer = sched_mid_timer.strftime('%Y-%m-%d %H:%M')
flag = 0
if __name__ == '__main__':
sched_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
timeRun(sched_time)
2.datetime
datetime转换为str
如果已经有了datetime对象,要把它格式化为字符串显示给用户,就需要转换为str,转换方法是通过strftime()实现的,同样需要一个日期和时间的格式化字符串:
>>> from datetime import datetime
>>> now = datetime.now()
>>> print(now.strftime('%a, %b %d %H:%M'))
Mon, May 05 16:28
datetime加减
对日期和时间进行加减实际上就是把datetime往后或往前计算,得到新的datetime。加减可以直接用+和-运算符,不过需要导入timedelta这个类:
>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> now
datetime.datetime(2015, 5, 18, 16, 57, 3, 540997)
>>> now + timedelta(hours=10)
datetime.datetime(2015, 5, 19, 2, 57, 3, 540997)
>>> now - timedelta(days=1)
datetime.datetime(2015, 5, 17, 16, 57, 3, 540997)
>>> now + timedelta(days=2, hours=12)
datetime.datetime(2015, 5, 21, 4, 57, 3, 540997)
可见,使用timedelta你可以很容易地算出前几天和后几天的时刻。
添加一个额外例子
import datetime, time
'''时间戳转换成日期,日期与字符串互换'''
timeStamp = 1231419600000
timeStamp = int(str(timeStamp)[:-3])
# 时间戳转换成字符串日期时间
dateArray = datetime.datetime.fromtimestamp(timeStamp)
# <class 'datetime.datetime'> 2009-01-08 21:00:00
print(type(dateArray), dateArray)
# 由日期格式转化为字符串
dd = dateArray.strftime("%Y-%m-%d")
print(type(dd), dd)
# 由字符串格式转化为日期格式
dd = datetime.datetime.strptime(dd, "%Y-%m-%d")
print(type(dd), dd)
d1 = datetime.datetime(2009, 1, 3)
day_num = (dd - d1).days
print(day_num)
print((dateArray - d1).days)
# 时间转换成时间戳
print("时间转换成时间戳")
now = datetime.datetime.now()
now_time = int(time.mktime(now.timetuple())) #datetime 转时间戳
print(now_time)
输出结果为:
<class 'datetime.datetime'> 2009-01-08 21:00:00
<class 'str'> 2009-01-08
<class 'datetime.datetime'> 2009-01-08 00:00:00
5
5
时间转换成时间戳
1575440693
https://www.jianshu.com/p/c741f6a31c1f
https://blog.csdn.net/cmzsteven/article/details/64906245
datetime,time 取当前时间的零点时辰
import datetime,time
dt = datetime.datetime.now()
day_str = datetime.datetime.strptime(dt.strftime("%Y-%m-%d"), "%Y-%m-%d")
day_time = int(time.mktime(time.strptime(dt.strftime("%Y-%m-%d"), "%Y-%m-%d")))
print("第二种变种,输出日期:", day_str, " 输出时间戳:", day_time)
结果:
第二种变种,输出日期: 2004-02-21 00:00:00 输出时间戳: 1077292800
2.定时
# coding:utf-8
import datetime
from threading import Timer
Minute = 1
def timedTask():
print("每隔10秒运行一次")
print(datetime.datetime.now())
t = Timer(10*Minute, timedTask)
t.start()
if __name__ == "__main__":
print('开启定时任务')
timedTask()









网友评论