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

本文介绍如何使用Python进行日期时间的基本操作,包括计算时间差、获取指定天数前的日期、精确时间、生成时间序列及时间格式转换等。适用于需要处理日期时间数据的Python开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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"

参考:

https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
http://stackoverflow.com/questions/993358/creating-a-range-of-dates-in-python
http://stackoverflow.com/questions/151199/how-do-i-calculate-number-of-days-betwen-two-dates-using-python
http://stackoverflow.com/questions/3183707/stripping-off-the-seconds-in-datetime-python

转载于:https://www.cnblogs.com/arkenstone/p/5609121.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值