pandas 在 Python 中将 datetime.datetime 对象转换为自纪元以来的天数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31687420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:41:35  来源:igfitidea点击:

Convert datetime.datetime object to days since epoch in Python

pythonpandasdatetimedate-formattingepoch

提问by brittenb

I've got a pandas.Seriesobject that might look like this:

我有一个pandas.Series可能看起来像这样的对象:

import pandas as pd
myVar = pd.Series(["VLADIVOSTOK 690090", "MAHE", NaN, NaN, "VLADIVOSTOK 690090", "2000-07-01 00:00:00"])

myVar[5]is parsed as a datetime.datetimeobject when the data is read into Python via pandas. I'm assuming that converting this value to the number of days since epoch (36708) isn't difficult at all. I'm just new to Python and don't know how to do it. Thanks in advance!

myVar[5]被解析为一个datetime.datetime当所述数据经由读入Python对象pandas。我假设将此值转换为自纪元 (36708) 以来的天数根本不困难。我只是 Python 新手,不知道该怎么做。提前致谢!

采纳答案by Padraic Cunningham

myVar = pd.Series(["VLADIVOSTOK 690090", "MAHE", "NaN", "NaN", "VLADIVOSTOK 690090", "2000-07-01 00:00:00"])

myVar[5] = pd.to_datetime(myVar[5]) - pd.datetime(1970,1,1)

print(myVar)
0     VLADIVOSTOK 690090
1                   MAHE
2                    NaN
3                    NaN
4     VLADIVOSTOK 690090
5    11139 days 00:00:00
dtype: object

回答by TigerhawkT3

I'm not sure where you're getting 36,708 days since the epoch (it's only been 16,644 days since January 1, 1970), but datetime.timedeltaobjects (used in date arithmetic) have a daysattribute:

我不确定自纪元以来的 36,708 天(自 1970 年 1 月 1 日以来只有 16,644 天),但datetime.timedelta对象(用于日期算术)有一个days属性:

>>> import datetime
>>> (datetime.datetime.utcnow() - datetime.datetime(1970,1,1)).days
16644

回答by bakhtiya

You can convert this to seconds since epoch first, then divide it out by the amount of seconds in a day (86,400 seconds in a day). Please note the integer division here - will not return a float.

您可以先将其转换为自纪元以来的秒数,然后将其除以一天中的秒数(一天中的 86,400 秒)。请注意这里的整数除法 - 不会返回浮点数。

from datetime import datetime
now = datetime.now()
seconds = now.strftime("%s") # seconds since epoch
days = int(seconds) / 86400 # days since epoch

I added the import and now as an example of a datetime object I can play with.

我添加了导入,现在作为我可以使用的日期时间对象的示例。