将 pandas.tslib.Timestamp 转换为日期时间 python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25852044/
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
Converting pandas.tslib.Timestamp to datetime python
提问by user1234440
I have a dftime series. I extracted the indexes and want to convert them each to datetime. How do you go about doing that? I tried to use pandas.to_datetime(x)but it doesn't convert it when I check after using type()
我有一个df时间序列。我提取了索引并希望将它们每个都转换为datetime. 你打算怎么做?我尝试使用pandas.to_datetime(x)但在使用后检查时它没有转换它type()
采纳答案by GoingMyWay
Just try to_datetime()
>>> import pandas as pd
>>> t = pd.tslib.Timestamp('2016-03-03 00:00:00')
>>> type(t)
pandas.tslib.Timestamp
>>> t.to_datetime()
datetime.datetime(2016, 3, 3, 0, 0)
>>> t.to_pydatetime()
datetime.datetime(2016, 3, 3, 0, 0)
Change to datetime.datetype
更改为datetime.date类型
>>> t.date()
datetime.date(2016, 3, 3)
update
更新
Thanks, @mjp, to_datetime()will be deprecated in the future, use to_pydatetime()instead!
谢谢,@ mjp,to_datetime()将来会被弃用,请to_pydatetime()改用!
In [4]: t.to_datetime()
/Users/qiuwei/Library/Python/2.7/lib/python/site-packages/IPython/core/interactiveshell.py:2881: FutureWarning: to_datetime is deprecated. Use self.to_pydatetime()
exec(code_obj, self.user_global_ns, self.user_ns)
Out[4]: datetime.datetime(2016, 3, 3, 0, 0)
回答by aikramer2
Assuming you are trying to convert pandas timestamp objects, you can just extract the relevant data from the timestamp:
假设您正在尝试转换 pandas 时间戳对象,您可以从时间戳中提取相关数据:
#Create the data
data = {1: tslib.Timestamp('2013-01-03 00:00:00', tz=None), 2: tslib.Timestamp('2013-01-04 00:00:00', tz=None), 3: tslib.Timestamp('2013-01-03 00:00:00', tz=None)}
#convert to df
df = pandas.DataFrame.from_dict(data, orient = 'index')
df.columns = ['timestamp']
#generate the datetime
df['datetime'] = df['timestamp'].apply(lambda x: datetime.date(x.year,x.month,x.day))
Of course, if you need seconds, minutes, and hours, you can include those as arguments for the function datetime.datetime as well.
当然,如果您需要秒、分和小时,您也可以将它们作为函数 datetime.datetime 的参数包含在内。
回答by sharon
I had the same issue, and tried the solution from @aikramer2, to add a column to my df of type 'datetime.datetime', but again i got a pandas data type:
我遇到了同样的问题,并尝试了@aikramer2 的解决方案,将一列添加到我的“datetime.datetime”类型的 df 中,但我再次得到了一个 Pandas 数据类型:
#libraries used -
import pandas as pd
import datetime as dt
#loading data into a pandas df, from a local file. note column [1] contains a datetime column -
savedtweets = pd.read_csv('/Users/sharon/Documents/ipython/twitter_analysis/conftwit.csv', sep='\t',
names=['id', 'created_at_string', 'user.screen_name', 'text'],
parse_dates={"created_at" : [1]})
print int(max(savedtweets['id'])) #535073416026816512
print type(savedtweets['created_at'][0]) # result is <class 'pandas.tslib.Timestamp'>
# add a column specifically using datetime.datetime library -
savedtweets['datetime'] = savedtweets['created_at'].apply(lambda x: dt.datetime(x.year,x.month,x.day))
print type(savedtweets['datetime'][0]) # result is <class 'pandas.tslib.Timestamp'>
i suspect pandas df cannot store a datetime.datetime data type. I got success when i made a plain python list to store the datetime.datetime values:
我怀疑 pandas df 无法存储 datetime.datetime 数据类型。当我制作一个简单的 python 列表来存储 datetime.datetime 值时,我获得了成功:
savedtweets = pd.read_csv('/Users/swragg/Documents/ipython/twitter_analysis/conftwit.csv', sep='\t',
names=['id', 'created_at_string', 'user.screen_name', 'text'],
parse_dates={"created_at" : [1]})
print int(max(savedtweets['id'])) #535073416026816512
print type(savedtweets['created_at'][0]) # <class 'pandas.tslib.Timestamp'>
savedtweets_datetime= [dt.datetime(x.year,x.month,x.day,x.hour,x.minute,x.second) for x in savedtweets['created_at']]
print savedtweets_datetime[0] # 2014-11-19 14:13:38
print savedtweets['created_at'][0] # 2014-11-19 14:13:38
print type(dt.datetime(2014,3,5,2,4)) # <type 'datetime.datetime'>
print type(savedtweets['created_at'][0].year) # <type 'int'>
print type(savedtweets_datetime) # <type 'list'>
回答by Kostyantyn
import time
time.strftime("%H:%M", time.strptime(str(x), "%Y-%m-%d %H:%M:%S"))
Note: x should be pandas.tslib.Timestamp (as it is in the question)
注意:x 应该是 pandas.tslib.Timestamp (因为它在问题中)
回答by giovannivl
This works for me, to create date for insertin MySQL, please try:
这对我insert有用,要在 MySQL 中创建日期,请尝试:
pandas_tslib = pandas_tslib.to_pydatetime()
pandas_tslib = "'" + pandas_tslib.strftime('%Y-%m-%d') + "'"
回答by Morris wong
Just an update to the question, I have tried the most upvoted answer, and it gives me this warning
只是对问题的更新,我尝试了最受好评的答案,它给了我这个警告
usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py:2910: FutureWarning: to_datetime is deprecated. Use self.to_pydatetime() exec(code_obj, self.user_global_ns, self.user_ns)
usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py:2910: FutureWarning: to_datetime 已弃用。使用 self.to_pydatetime() exec(code_obj, self.user_global_ns, self.user_ns)
And suggest me to use to_pydatetime()
并建议我使用to_pydatetime()
For example
例如
sample = Timestamp('2018-05-02 10:08:54.774000')
sample = Timestamp('2018-05-02 10:08:54.774000')
sample.to_datetime()will return datetime.datetime(2018, 4, 30, 10, 8, 54, 774000)
sample.to_datetime()将返回 datetime.datetime(2018, 4, 30, 10, 8, 54, 774000)
回答by smontanaro
You can convert a Timestamp to a Python datetime object with to_pydatetime(), but it seems that when applied to an entire column that conversion is thwarted:
您可以使用 to_pydatetime() 将时间戳转换为 Python 日期时间对象,但似乎当应用于整个列时,转换会受阻:
>>> ts = pd.tslib.Timestamp.now()
>>> type(ts)
<class 'pandas._libs.tslibs.timestamps.Timestamp'>
>>> type(ts.to_pydatetime())
<class 'datetime.datetime'>
>>> df = pd.DataFrame({"now": [datetime.datetime.utcnow()] * 10})
>>> type(df['now'].iloc[0])
<class 'pandas._libs.tslibs.timestamps.Timestamp'>
>>> df['now2'] = df['now'].apply(lambda dt: dt.to_pydatetime())
>>> type(df['now2'].iloc[0])
<class 'pandas._libs.tslibs.timestamps.Timestamp'>
Not sure what to make of that. (There are some situations where Pandas' Timestamp object isn't a perfect replacement for Python's datetime object, and you want the real thing.)
不知道该怎么做。(在某些情况下,Pandas 的 Timestamp 对象不是 Python 的 datetime 对象的完美替代品,而您想要真实的东西。)
回答by gies0r
As an alternative solution if you have two separate fields(one for date; one for time):
如果您有两个单独的字段(一个用于日期;一个用于时间),作为替代解决方案:
Convert to datetime.date
转换为datetime.date
df['date2'] = pd.to_datetime(df['date']).apply(lambda x: x.date())
Convert to datetime.time
转换为datetime.time
df['time2'] = pd.to_datetime(df['time']).apply(lambda x: x.time())
Afterwards you can combine them:
之后你可以组合它们:
df['datetime'] = df.apply(lambda r : pd.datetime.combine(r['date2'],r['time2']),1)
Adapted this post
改编了这篇文章
回答by Francesco Boi
In my case I could not get a correct output even when specifying the format: I used to get always the year 1970.
就我而言,即使指定格式,我也无法获得正确的输出:我过去总是得到 1970 年。
Actually what solved my problem was to specify the unitparameter to the function since my timestamps have seconds granularity:
实际上,解决我的问题的是指定unit函数的参数,因为我的时间戳具有秒粒度:
df_new = df
df_new['time'] = pandas.to_datetime(df['time'], unit='s')

