Python使用时间戳
2015-07-10 10:31
489 查看
1.将字符串的时间转换为时间戳 方法: a = "2013-10-10 23:40:00" 将其转换为时间数组 importtime timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S") 转换为时间戳: timeStamp = int(time.mktime(timeArray)) timeStamp == 1381419600 2.字符串格式更改 如a = "2013-10-10 23:40:00",想改为 a = "2013/10/10 23:40:00" 方法:先转换为时间数组,然后转换为其它格式 timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S") otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray) 3.时间戳转换为指定格式日期: 方法一: 利用localtime()转换为时间数组,然后格式化为须要的格式,如 timeStamp = 1381419600 timeArray = time.localtime(timeStamp) otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) otherStyletime == "2013-10-10 23:40:00" 方法二: importdatetime timeStamp = 1381419600 dateArray = datetime.datetime.utcfromtimestamp(timeStamp) otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S") otherStyletime == "2013-10-10 23:40:00" 4.获取当前时间并转换为指定日期格式 方法一: importtime 获得当前时间时间戳 now = int(time.time()) ->这是时间戳 转换为其它日期格式,如:"%Y-%m-%d %H:%M:%S" timeArray = time.localtime(timeStamp) otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) 方法二: importdatetime 获得当前时间 now = datetime.datetime.now() ->这是时间数组格式 转换为指定的格式: otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S") 5.获得三天前的时间 方法: importtime importdatetime 先获得时间数组格式的日期 threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 3)) 转换为时间戳: timeStamp = int(time.mktime(threeDayAgo.timetuple())) 转换为其它字符串格式: otherStyleTime = threeDayAgo.strftime("%Y-%m-%d %H:%M:%S") 注:timedelta()的參数有:days,hours,seconds,microseconds 6.给定时间戳,计算该时间的几天前时间: timeStamp = 1381419600 先转换为datetime importdatetime importtime dateArray = datetime.datetime.utcfromtimestamp(timeStamp) threeDayAgo = dateArray - datetime.timedelta(days = 3) 參考5,能够转换为其它的随意格式了
相关文章推荐
- Python中获取异常(Exception)信息
- python中sorted()函数的应用
- 【Python】Windows版本的Python开发环境的配置,Helloworld,Python中文问题,输入输出、条件、循环、数组、类
- Python Xpath与Regex的区别
- Python什么是二次开发的意义?python在.net项目采用
- 【Python】python环境的搭建之windows篇
- python基础之数据类型语句
- Python笔记:random模块常用函数
- Python中的一些陷阱与技巧小结
- python beautifulsoup抓取京东商品名称和价格
- Python实现检测代理IP是否可以翻墙
- Scikit-Learn:开源的机器学习Python模块
- python文件操作
- ADT in python DEMO
- python的绿色版本
- rebot的使用
- Robot Framework安装指南
- 如何编写Robot Framework测试用例1---(基本格式篇)
- 自动化测试框架 RobotFramework 用户说明书中文版
- 自动化测试平台 Robot Framework 快速入门