2014-08-27 116 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