将列表中的第一个元素从字符串更改为日期 [英] Change the first element in a list from string to date
问题描述
我有以下文本文件,其中包含以下列表:
I have the following text file that has these lists :
['2009-06-12 14:19:28 ', '0']
['2009-06-13 00:58:10 ', '0']
['2009-06-13 01:00:25 ', '0']
['2009-06-15 03:24:23 ', '0']
['2009-06-25 17:50:46 ', '0']
['2009-06-29 20:54:52 ', '0']
['2009-06-30 20:31:19 ', '0']
['2009-07-09 03:01:25 ', '0']
['2009-07-12 14:45:53 ', '0']
['2009-07-12 15:09:38 ', '0']
第二个元素是整数,但是,第一个元素是一个字符串。我需要每个lis的第一个元素是一个日期而不是字符串?
我试过这段代码:
The second element is an integer, however, the first element is a string. I need the first element of each lis to be a date instead of string?
I tried this code:
word[0]=datetime.strptime(word[0],'%Y/%m/%d %H:%M:%S')
但我收到此错误:
but I get this error:
ValueError: time data '2009-04-02 22:50:06 ' does not match format '%Y/%m/%d %H:%M:%S'
我清理数据的当前代码如下:
the current code I have that cleans the data is the following:
with open('newdata.txt') as f:
for line in f:
tweet=re.sub(r'T\t',"",line)
t=re.sub(r'W\t',"\/\/",tweet)
data=t.split("\/\/")
sentiment_value= s.sentiment(data[1])
data.append(sentiment_value)
words = [w.replace('pos', '1') for w in data]
word=[w.replace('neg','0')for w in words]
del word[1]
print(word)
我的尝试:
我试过这段代码:
What I have tried:
I tried this code:
word[0]=datetime.strptime(word[0].strip(),'%Y/%m/%d %H:%M:%S')
但是我收到了这个错误:
but I get this error:
ValueError: time data '2009-04-02 22:50:06 ' does not match format '%Y/%m/%d %H:%M:%S'
推荐答案
初看......似乎你需要更换:
On the first look... Seems you need to replace:
dt = datetime.strptime("2009-04-02 22:50:06",'%Y/%m/%d %H:%M:%S')
with:
with:
dt = datetime.strptime("2009-04-02 22:50:06", "%Y-%m-%d %H:%M:%S")
见:
将字符串转换为日期时间 [ ^ ]
8.1。 datetime - 基本日期和时间类型 - Python 3.6.6rc1文档 [ ^ ]
但是...... 文档 [ ^ ]也声明:
See:
Converting Strings To Datetime[^]
8.1. datetime — Basic date and time types — Python 3.6.6rc1 documentation[^]
But... the documentation[^] states also:
使用不完整或含糊不清的ISO 8601指令调用strptime()将引发 ValueError
。
(.. 。)
因为格式取决于当前的语言环境,所以在对输出值进行假设时应该小心。字段排序会有所不同(例如,月/日/年
与日/月/年
) ,输出可能包含使用区域设置的默认编码编码的Unicode字符(例如,如果当前区域设置是ja_JP,则默认编码可以是eucJP,SJIS或utf-8中的任何一个;使用区域设置.getlocale()
确定当前语言环境的编码。
Calling strptime() with incomplete or ambiguous ISO 8601 directives will raise a ValueError
.
(...)
Because the format depends on the current locale, care should be taken when making assumptions about the output value. Field orderings will vary (for example, "month/day/year
" versus "day/month/year
"), and the output may contain Unicode characters encoded using the locale’s default encoding (for example, if the current locale is ja_JP, the default encoding could be any one of eucJP, SJIS, or utf-8; use locale.getlocale()
to determine the current locale’s encoding).
这篇关于将列表中的第一个元素从字符串更改为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!