![4e6d0f7c1c9564ad573b5b40d19e95a1.png](https://img-blog.csdnimg.cn/img_convert/4e6d0f7c1c9564ad573b5b40d19e95a1.png)
昨天快下班时的需求,对时间进行偏移计算。找了一篇介绍Pandas时间序列的文章,大致翻译一下(把英文粘贴到谷歌翻译,再把中文拷贝过来)。
原文:https://jakevdp.github.io/PythonDataScienceHandbook/03.11-working-with-time-series.html
原文的版权声明:
This is an excerpt from the Python Data Science Handbook by Jake VanderPlas; Jupyter notebooks are available on GitHub.
The text is released under the CC-BY-NC-ND license, and code is released under the MIT license. If you find this content useful, please consider supporting the work by buying the book!
需求的解决方案:https://stackoverflow.com/questions/46399204/add-pandas-timedelta-to-a-datetime64-series-or-column-in-dataframe
delta = pd.Timedelta(hours=5, minutes=30)
df['ts1'] = df['ts'] - delta
df['ts2'] = df['ts'] + delta
以下为文章翻译:
Pandas是在金融行业的背景下开发的,正如您所料,它包含一组相当广泛的工具,用于处理日期,时间和时间索引数据。 日期和时间数据有几种,我们将在这里讨论:
- 时间戳指特定时刻(例如,2015年7月4日上午7:00)。
- 时间间隔和周期,指特定开始和结束点之间的时间长度,例如,2015年。周期通常指时间间隔的特殊情况,每个时间间隔具有统一的长度,并且不重叠(例如,24小时的周期构成天)。
- 时间增量(delta)或持续时间(duration)指精确的时间长度(例如,持续时间为22.56秒)。
在本节中,我们将介绍如何在Pandas中使用这些类型的日期/时间数据。 这篇短文不是Python或Pandas中可用的时间序列工具的完整指南,而是作为用户如何处理时间序列的广泛概述。 我们将首先简要讨论在Python中处理日期和时间的工具,然后再更具体地讨论Pandas提供的工具。 在列出一些更深入的资源之后,我们将回顾一些在Pandas中处理时间序列数据的简短示例。
Python中的日期和时间
Python世界有许多可用的日期,时间,增量和时间表的表示形式。 虽然Pandas提供的时间序列工具往往对数据科学应用程序最有用,但查看它们与Python中使用的其他包的关系会很有帮助。
原生Python日期和时间:datetime和dateutil
Python处理日期和时间的基本对象驻留在内置的datetime模块中。 与第三方dateutil模块一起,您可以使用它在日期和时间快速执行许多有用的功能。 例如,您可以使用datetime类型手动构建日期:
from datetime import datetime
datetime(year=2015, month=7, day=4)
输出:datetime.datetime(2015, 7, 4, 0, 0)
或者,使用dateutil模块,您可以从各种字符串格式解析日期:
from dateutil import parser
date = parser.parse("4th of July, 2015")
date
输出:datetime.datetime(2015, 7, 4, 0, 0)
拿到datetime对象后,您可以执行打印星期几等操作:
date.strftime('%A')
输出:'Saturday'
在上述代码中,我们使用了一个标准字符串格式代码('%A')来打印日期,此类代码您可以在Python的datetime文档(datetime documentation)的strftime部分找到详细信息(strftime section ÿ