问题描述
我正在尝试将 pandas.Timestamp
转换为内置的python datetime
.我尝试了以下方法:
I was tinkering around with converting pandas.Timestamp
to the built in python datetime
. I tried the following:
pandas_time = pd.Timestamp(year=2020, day=4, month=2, hour=0, minute=0, second=1)
pandas_ts = pandas_time.timestamp()
datetime_time = datetime.datetime.fromtimestamp(pandas_ts)
datetime_ts = datetime_time.timestamp()
查看变量可得出以下信息:
Looking at the variables gives this:
pandas_time: 2020-02-04 00:00:01
datetime_time: 2020-02-04 01:00:01
pandas_ts: 1580774401.0
datetime_ts: 1580774401.0
因此它们都具有相同的时间戳,但日期相差一小时.当我尝试另一种方法时,我得到了:
So they both have the same timestamp but the dates differ by one hour.When I tried it the other way around, I got this:
datetime_time = datetime.datetime(year=2020, day=4, month=2, hour=0, minute=0, second=1)
datetime_ts = datetime_time.timestamp()
pandas_time = pd.Timestamp(datetime_time)
pandas_ts = pandas_time.timestamp()
pandas_time: 2020-02-04 00:00:01
datetime_time: 2020-02-04 00:00:01
pandas_ts: 1580774401.0
datetime_ts: 1580770801.0
现在日期相同,但是时间戳相差3600(1小时).我确实知道我可以使用pandas to_pydatetime
从pandas Timestamp转换为python datetime,但是我想知道为什么会出现这种差异.他们的出发点定义不同吗?如果是这样,为什么?
Now the dates are the same but the timestamps differ by 3600 (1 hour).I do know that I could use pandas to_pydatetime
for conversion from pandas Timestamp to python datetime but I'm wondering why this difference occurs. Are their starting points defined differently? And if so, why?
推荐答案
如果您查看 datetime
文档,则该文档是为 .fromtimestamp(timestamp)
If you look at the datetime
documentation it is written for .fromtimestamp(timestamp)
因此它返回本地日期
.就是这样.因此,您需要告诉它明确使用 utc
,而 pandas
默认使用utc.
So it returns local date
. That's it. So you need to tell it to use utc
explicitly whereas pandas
uses utc by default.
pandas_time = pd.Timestamp(year=2020, month=2, day=4, hour=0, minute=0, second=1)
pandas_ts = pandas_time.timestamp()
datetime_time = datetime.datetime.fromtimestamp(pandas_ts, tz=timezone.utc)
datetime_ts = datetime_time.timestamp()
第二种情况类似
datetime_time = datetime.datetime(year=2020, day=4, month=2, hour=0, minute=0, second=1, tzinfo=timezone.utc)
datetime_ts = datetime_time.timestamp()
pandas_time = pd.Timestamp(datetime_time)
pandas_ts = pandas_time.timestamp()
从您的问题来看,您似乎生活在UTC + 1国家:p
From your question it seems you are living in a UTC+1 country :p
这篇关于 pandas 时间戳和日期时间之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!