python3.6 日期时间格式化

获取当前日期:time.time()

获取元组形式的时间戳:time.local(time.time())

格式化日期的函数(基于元组的形式进行格式化):

(1)time.asctime(time.local(time.time()))

(2)time.strftime(format[,t])

将格式字符串转换为时间戳:

time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')

延迟执行:time.sleep([secs]),单位为秒

import time
#当前时间
print(time.time())
#时间戳形式
print(time.localtime(time.time()))
#简单可读形式
print(time.asctime( time.localtime(time.time()) ))
# 格式化成2019-05-07 14:17:55形式
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
# 格式化成Tue May  7 14:17:30 2019形式
print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))
# 将格式字符串转换为时间戳
a = "Tue May  7 14:17:30 2019"
print(time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y")))

输出如下:

# python3 py_datetime.py 
1557210279.199081
time.struct_time(tm_year=2019, tm_mon=5, tm_mday=7, tm_hour=14, tm_min=24, tm_sec=39, tm_wday=1, tm_yday=127, tm_isdst=0)
Tue May  7 14:24:39 2019
2019-05-07 14:24:39
Tue May 07 14:24:39 2019
1557209850.0
"""
 Requirements:获取当前时间,和预定的时间进行比较,若当前时间大于预定时间则执行脚本,若当前时间小于
 预定时间则休眠10s。
"""
import time
import sys
import os
#判断当前时间是否超过某个输入的时间
def func_gettime(s):
    if time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))>s:
        return True
    else:
        return False

while(1):
    if func_gettime('2019-05-07 14:33:00'):
        #调用某个路径下的脚本的简便方法
        os.system("python3 /root/py_datetime.py")
        break
    else:
        print("current_time:",time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        time.sleep(10)
        print("sleep 10s!")
        continue

 

输出信息如下: 

# python3 py_decide.py 
current_time: 2019-05-07 14:32:12
sleep 10s!
current_time: 2019-05-07 14:32:22
sleep 10s!
current_time: 2019-05-07 14:32:32
sleep 10s!
current_time: 2019-05-07 14:32:42
sleep 10s!
current_time: 2019-05-07 14:32:52
sleep 10s!
1557210782.5852695
time.struct_time(tm_year=2019, tm_mon=5, tm_mday=7, tm_hour=14, tm_min=33, tm_sec=2, tm_wday=1, tm_yday=127, tm_isdst=0)
Tue May  7 14:33:02 2019
2019-05-07 14:33:02
Tue May 07 14:33:02 2019
1557209850.0
>>> import datetime as dt
>>> print(dt.datetime.now())
2019-05-07 14:45:12.321748
>>> print(dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
2019-05-07 14:45:24
>>> 
>>> print((dt.datetime.now()+datetime.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S"))
2019-05-07 15:45:32

时间的加减:

datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)


datetime.date(year, month, day)



https://docs.python.org/3.6/library/datetime.html#timedelta-objects

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客 返回首页