浅谈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"
相关推荐
deepSTEM 2020-08-16
wulaxiaohei 2020-06-06
香帅 2020-06-05
bingxuelengmei 2020-05-13
夕加加 2020-04-23
qingsongzdq 2020-02-02
超级赛亚人 2013-05-31
yishujixiaoxiao 2019-12-31
85231843 2019-12-11
hzcyhujw 2019-11-29
wwwjun 2019-10-20
Imliao 2019-10-15
dly 2015-05-29
chenzelin 2018-05-30
云计算和大数据 2018-05-30
syumilai 2019-08-08
yunhuaikong 2019-07-25
lovelily 2011-09-09
zrenpro 2011-06-13