更新:我查看了您的代码并发现了一些错误类型。
此外,您似乎没有添加串联。
我都整理好了。
错误输入:
你写道:
for k, line in enumerate(lines):
if k > (int(header_line)):
data_pre = line.strip().split(',')
stDate = data_pre[0].replace("\"", "")
print stDate # got 1998-04-18 16:48:36.76
dat_time = datetime.datetime.strptime(stDate,
'%Y-%m-%d %H:%M:%S.%f')
mic_sec = dat_time.microsecond
timcon = calendar.timegm(dat_time.timetuple())*1000000 + mic_sec
strDate = "\"" + strDate + "\""
# ^ This line is wrong
# It should say:
# strDate = "\"" + stDate + "\""
print stDate # got "1998-04-18 16:48:36.76"
# ^ This line is wrong
# It should say:
# print strDate
实施上述更改后,我们现在可以将“+”.0“”添加到您的代码示例中
(先尝试运行它,确保您了解它在做什么,然后再继续):
import time
import datetime
import calendar
A = "1998-04-18 16:48:36.76,0,38"
B = "1998-04-18 16:48:37,5,33"
# Run the Code for B
data_pre = B.strip().split(',')
print data_pre
stDate = data_pre[0].replace("\"", "")
print "stDate before: ", stDate
### Addition of Addition of .0
# Here, we try to convert to datetime format using the format
# '%Y-%m-%d %H:%M:%S.%f'
try:
dat_time = datetime.datetime.strptime(stDate,
'%Y-%m-%d %H:%M:%S.%f')
# If that doesn't work, we add ".4" to the end of stDate
# (You can change this to ".0")
# We then retry to convert stDate into datetime format
except:
stDate = stDate + ".4"
dat_time = datetime.datetime.strptime(stDate,
'%Y-%m-%d %H:%M:%S.%f')
print "stDate after: ", stDate
###
print "dat_time: ", dat_time
mic_sec = dat_time.microsecond
print "mic_sec: ", mic_sec
timcon = calendar.timegm(dat_time.timetuple())*1000000 + mic_sec
print "timecon: ", timcon
strDate = "\"" + stDate + "\""
print "strDate: ", strDate
因此,举个例子:
A = "1998-04-18 16:48:36.76,0,38"
B = "1998-04-18 16:48:37,5,33"
# Note the difference ^^
# Output for B:
['1998-04-18 16:48:37', '5', '33']
stDate before: 1998-04-18 16:48:37
stDate after: 1998-04-18 16:48:37.4
dat_time: 1998-04-18 16:48:37.400000
mic_sec: 400000
timecon: 892918117400000
strDate: "1998-04-18 16:48:37.4"
# Output for A:
['1998-04-18 16:48:36.76', '0', '38']
stDate before: 1998-04-18 16:48:36.76
dat_time: 1998-04-18 16:48:36.760000
mic_sec: 760000
timecon: 892918116760000
strDate: "1998-04-18 16:48:36.76"
将 Everything 集成到您的主循环中。这就是你想要的整体:
for k, line in enumerate(lines):
if k > (int(header_line)):
data_pre = line.strip().split(',')
stDate = data_pre[0].replace("\"", "")
print stDate
try:
dat_time = datetime.datetime.strptime(stDate,
'%Y-%m-%d %H:%M:%S.%f')
except:
stDate = stDate + ".4"
dat_time = datetime.datetime.strptime(stDate,
'%Y-%m-%d %H:%M:%S.%f')
mic_sec = dat_time.microsecond
timcon = calendar.timegm(dat_time.timetuple())*1000000 + mic_sec
strDate = "\"" + stDate + "\""
# ^ Changed this line
print strDate
# ^ Changed this line
原答案:
你不能追加到一个字符串。
一种选择是使用A + B
A = "1998-04-18 16:48:36"
B = ".0"
C = A + B
C = "1998-04-18 16:48:36.0"
你也可以使用str.join:
D = "".join([A,B])
D = '1998-04-18 16:48:36.0'
有关详细信息,请参阅此问题的答案:Which is the preferred way to concatenate a string in Python?