我有2个日期列(开始和结束)在一个数据框中的日期是以下字符串格式'%Y-%m-%d%H:%M:%S.% F'。我怎样才能改变这些日期格式在Python中?我还想创建一个新列,显示结束日期和开始日期之间的天数差异。蟒蛇改变字符串
在此先感谢!
我有2个日期列(开始和结束)在一个数据框中的日期是以下字符串格式'%Y-%m-%d%H:%M:%S.% F'。我怎样才能改变这些日期格式在Python中?我还想创建一个新列,显示结束日期和开始日期之间的天数差异。蟒蛇改变字符串
在此先感谢!
如果您使用的是最新的熊猫版本,你可以传递一个格式参数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
谢谢!它的工作完美:) – roland 2014-08-28 02:47:45
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
请看第一部分的[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