2014-08-27 120 views
1

我有2个日期列(开始和结束)在一个数据框中的日期是以下字符串格式'%Y-%m-%d%H:%M:%S.% F'。我怎样才能改变这些日期格式在Python中?我还想创建一个新列,显示结束日期和开始日期之间的天数差异。蟒蛇改变字符串

在此先感谢!

+2

请看第一部分的[time.strptime](https://docs.python.org/3/library/time.html#time.strptime)吗?然后你可以减去另一个,最后得到一个[timedelta](https://docs.python.org/2/library/datetime.html#datetime.timedelta)对象 – bvidal 2014-08-27 23:43:17

回答

4

如果您使用的是最新的熊猫版本,你可以传递一个格式参数to_datetime

In [11]: dates = ["2014-08-27 19:53:06.000", "2014-08-27 19:53:15.002"] 

In [12]: pd.to_datetime(dates, format='%Y-%m-%d %H:%M:%S.%f') 
Out[12]: 
<class 'pandas.tseries.index.DatetimeIndex'> 
[2014-08-27 19:53:06, 2014-08-27 19:53:15.002000] 
Length: 2, Freq: None, Timezone: None 

注:这是不是在这种情况下,有必要通过格式,但它可能更快/更严格:

In [13]: pd.to_datetime(dates,) 
Out[13]: 
<class 'pandas.tseries.index.DatetimeIndex'> 
[2014-08-27 19:53:06, 2014-08-27 19:53:15.002000] 
Length: 2, Freq: None, Timezone: None 
+0

谢谢!它的工作完美:) – roland 2014-08-28 02:47:45

0

datetime模块拥有您需要用日期进行游戏的所有功能。请注意,在格式你描述%Y-%m-%d %H:%M:%S.%f%f不会出现在known directives并且不包括在我的答案

from datetime import datetime 
dates = ["2014-08-27 19:53:06", "2014-08-27 19:53:15"] 
# That's where the conversion happens from string to datetime objects 
datetimes = [datetime.strptime(date, "%Y-%m-%d %H:%M:%S") for date in dates] 
print datetimes 
>> [datetime.datetime(2014, 8, 27, 19, 53, 6), datetime.datetime(2014, 8, 27, 19, 53, 15) 
# Here a simple subtraction will give you the result you are looking for return a timedelta object 
delta = datetimes[1] - datetimes[0] 
print type(delta), delta 
>> <type 'datetime.timedelta'>, 0:00:09 
+1

请参见下表:包括https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior,'%f' *。 – joris 2014-08-28 06:27:11

+0

谢谢@joris我必须开始使用python 3! – bvidal 2014-08-28 12:59:50

+0

你的链接也是python 3 :-),但区别在于你链接到'time'模块,而这里'datetime'是相关的 – joris 2014-08-28 13:03:09