迄今为止的Python字符串数字

时间:2015-12-29 11:02:55

标签: python pandas

我正在尝试使用时间戳字段处理数据。时间戳看起来像这样:

' 20151229180504511' (年,月,日,小时,分钟,秒,毫秒)

并且是一个python字符串。我试图将其转换为python datetime对象。这是我尝试过的(使用熊猫):

data['TIMESTAMP'] = data['TIMESTAMP'].apply(lambda x:datetime.strptime(x,"%Y%b%d%H%M%S"))

# returns error time data '20151229180504511' does not match format '%Y%b%d%H%M%S'

所以我加上毫秒:

data['TIMESTAMP'] = data['TIMESTAMP'].apply(lambda x:datetime.strptime(x,"%Y%b%d%H%M%S%f")) 
# also tried with .%f all result in a format error

尝试使用dateutil.parser:

data['TIMESTAMP'] = data['TIMESTAMP'].apply(lambda s: dateutil.parser.parse(s).strftime(DateFormat)) 
# results in OverflowError: 'signed integer is greater than maximum'

还尝试使用pandas函数转换这些条目:

data['TIMESTAMP'] = pd.to_datetime(data['TIMESTAMP'], unit='ms', errors='coerce') 
# coerce does not show entries as NaT

我确保空白消失了。转换为字符串,整数和浮点数。到目前为止没有运气 - 相当困难。

有什么想法吗?

P.S。背景信息:数据在Android应用程序中生成为java.util.Calendar类,然后转换为Java中的字符串,写入csv然后发送到python服务器,我在其中使用pandas {{1 }}。

2 个答案:

答案 0 :(得分:4)

试试: datetime.strptime(x,"%Y%m%d%H%M%S%f")

你错过了这个:

  • %b :月份为区域设置的缩写名称。
  • %m :月份为零填充十进制数。

答案 1 :(得分:3)

%b适用于基于区域设置的月份名称缩写,例如JanFeb等。 使用%m 2个月的数字:

In [36]: df = pd.DataFrame({'Timestamp':['20151229180504511','20151229180504511']})

In [37]: df
Out[37]: 
           Timestamp
0  20151229180504511
1  20151229180504511

In [38]: pd.to_datetime(df['Timestamp'], format='%Y%m%d%H%M%S%f')
Out[38]: 
0   2015-12-29 18:05:04.511
1   2015-12-29 18:05:04.511
Name: Timestamp, dtype: datetime64[ns]