Python格式化日期时间操作示例

yipeiwu_com6年前Python基础

本文实例讲述了Python格式化日期时间的方法。分享给大家供大家参考,具体如下:

常用的时间函数如下

获取当前日期: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]),单位为秒

例1:

# -*- coding:utf-8 -*-
import time
#当前时间
print time.time()
#时间戳形式
print time.localtime(time.time())
#简单可读形式
print time.asctime( time.localtime(time.time()) )
# 格式化成2016-03-20 11:45:39形式
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
# 格式化成Sat Mar 28 22:24:24 2016形式
print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) 
# 将格式字符串转换为时间戳
a = "Sat Mar 28 22:24:24 2016"
print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))

输出:

1481036968.19
time.struct_time(tm_year=2016, tm_mon=12, tm_mday=6, tm_hour=23, tm_min=9, tm_sec=28, tm_wday=1, tm_yday=341, tm_isdst=0)
Tue Dec 06 23:09:28 2016
2016-12-06 23:09:28
Tue Dec 06 23:09:28 2016
1459175064.0

例2:某时间与当前比较,如果大于当前时间则调用某个脚本,否则等待半个小时候后继续判断

# -*- coding:utf-8 -*-
import time
import sys
import os
#判断当前时间是否超过某个输入的时间
def Fuctime(s):
  if time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))>s:
    return True
  else:
    return False
while(1):
  if Fuctime('2016-12-05 00:00:00'):
    #调用某个路径下的脚本的简便方法
    os.system("python ./../day_2/Prime.py ./../day_2/inti_prime.txt ./../day_2/res_prime.txt")
    break
  else:
    time.sleep(1800)
    continue

PS:这里再为大家推荐几款关于日期与天数计算的在线工具供大家使用:

在线日期/天数计算器:
http://tools.jb51.net/jisuanqi/date_jisuanqi

在线万年历日历:
http://tools.jb51.net/bianmin/wannianli

在线阴历/阳历转换工具:
http://tools.jb51.net/bianmin/yinli2yangli

Unix时间戳(timestamp)转换工具:
http://tools.jb51.net/code/unixtime

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python日期与时间操作技巧总结》、《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python中的exec、eval使用实例

通过exec可以执行动态Python代码,类似Javascript的eval功能;而Python中的eval函数可以计算Python表达式,并返回结果(exec不返回结果,print(e...

python是否适合网页编程详解

Python是一种计算机程序设计语言。是一种面向对象的动态类型语言,最初被设计用于编写自动化脚本(shell),随着版本的不断更新和语言新功能的添加,越来越多被用于独立的、大型项目的开发...

python装饰器-限制函数调用次数的方法(10s调用一次)

这是博主最近一家大公司的面试题,写一个装饰器,限制函数每10s调用一次。当时是笔试的,只写了大概的代码,回来后温习了python装饰器的基础知识,把代码写完了。决定写篇博客记录下。 装饰...

python opencv3实现人脸识别(windows)

本文实例为大家分享了python人脸识别程序,大家可进行测试 #coding:utf-8 import cv2 import sys from PIL import Ima...

python中for循环把字符串或者字典添加到列表的方法

python中for循环把字符串或者字典添加到列表的方法

python中如何for循环把字符串添加到列表? 实例: 1.单个字符串用for循环添加到列表中: # 把L1中的字符串添加到列表alist里面 L1 = 'MJlifeBlog'...