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使用reportlab将目录下所有的文本文件打印成pdf的方法

本文实例讲述了Python使用reportlab将目录下所有的文本文件打印成pdf的方法。分享给大家供大家参考。具体实现方法如下: # -*- coding: utf8 -*- #...

python 中if else 语句的作用及示例代码

引入:if-else的作用,满足一个条件做什么,否则做什么。 if-else语句语法结构 if 判断条件: 要执行的代码 else: 要执行的代码 判断条件:一般为关系表达式或bool类...

python下读取公私钥做加解密实例详解

python下读取公私钥做加解密实例详解 在RSA有一种应用模式是公钥加密,私钥解密(另一种是私钥签名,公钥验签)。下面是Python下的应用举例。 假设我有一个公钥文件,rsa_pub...

Python简单读取json文件功能示例

本文实例讲述了Python简单读取json文件功能。分享给大家供大家参考,具体如下: read_json.json: { "rule":{ "namespace":"st...

利用Python代码实现一键抠背景功能

利用Python代码实现一键抠背景功能

前言 又是一个逛csdn发现的一个有趣的小项目,可以一键抠背景,需要用到removebg模块及其API,API可从其官网免费获取,网址如下https://www.remove.bg/zh...