手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Python中用datetime包进行对时间的一些操作

[日期:2016-06-23] 来源:Linux社区  作者:arkenstone [字体: ]

Python中用datetime包进行对时间的一些操作

1. 计算给出两个时间之间的时间差

import datetime as dt
# current time
cur_time = dt.datetime.today()
# one day
pre_time = dt.date(2016, 5, 20) # eg: 2016.5.20
delta = cur_time - pre_time
# if you want to get discrepancy in days
print delta.days
# if you want to get discrepancy in hours
print delta.hours
# and so on

2. 获取n天前的时间

cur_time = dt.now()
# previous n days
pre_time = dt.timedelta(days=n)

3. 将给定的时间精确到天或者其他单位

cur_time = dt.now()
# get day of current time
cur_day = cur_time.replace(hour=0, minute=0, second=0, mircrosecond=0)

4. 获取一连串的时间序列(返回list)

cur_time = dt.datetime.today()
datelist = [cur_time - dt.timedelta(days=x) for x in range(0, 100)]

或者

import pandas as pd
datelist =  pd.date_range(pd.datetime.today(), periods=100).tolist()

5. 将时间字符串转化为datetime类型

date_formate = "%Y-%m-%d" # year-month-day
time = dt.strptime('2016-06-22', date_format)

6. 将时间类型转化为字符串类型

time_str = dt.strftime("%Y-%m-%d", dt.now()) # return like "2016-06-22"

CentOS上源码安装Python3.4  http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

Ubuntu下用Python搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的详细介绍请点这里
Python 的下载地址请点这里

本文永久更新链接地址http://www.linuxidc.com/Linux/2016-06/132589.htm

linux
相关资讯       Python datetime操作  Python时间操作 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款