我有一个巨大的日志文件,时间戳格式如下:
08/07/2013 11:40:08 PM INFO
我想使用python将其转换为mysql时间戳,比如:
^{pr2}$我已经编写了一个python脚本来实现这一点,但是我想知道是否已经编写了一些内置的python包/函数来轻松、高效地完成时间戳例程的工作。在
由于数据的“信息传递”是我日常工作的一部分,因此,对于我代码的效率、新函数的使用甚至是新工具的使用提出任何建议都将不胜感激。在
(注意:输入文件由^A分隔,同时我还将其转换为csv)
($猫输出.file|Pythoncsv.py文件>;输出.csv)在
import sys
def main():
for line in sys.stdin:
line = line[:-1]
cols = line.split(chr(1))
cols[0] = convertTime(cols[0])
cols = [ '"' + col + '"' for col in cols ]
print ",".join(cols)
def convertTime(loggingTime):
#mysqlTime example: 2013-04-11 13:18:02
#loggingTime example: 08/07/2013 11:40:08 PM INFO
#DATE
month, day, year = loggingTime[0:10].split('/')
date = '/'.join([year,month,day])
#TIME
hour, minute, second = loggingTime[11:19].split(':')
flag = loggingTime[20:22]
if flag == 'PM':
hour = str(int(hour) + 12)
time = ":".join([hour, minute, second])
mysqlTime = date + " " + time
return mysqlTime
if __name__ == '__main__':
main()
{{cd2>要重新格式化{cd2>,然后使用}?在
但是请注意,}可以为不同的区域设置AM/PM的不同格式;因此为了安全起见,您可能需要在开始时运行以下代码:
^{pr2}$strptime
和strftime
可能受当前区域设置的影响,您可能需要将区域设置为C
(它也由datetime
模块内部使用),因为{按照建议,用如下的strptime转换它:
^{pr2}$由于“INFO”字符串(编辑:不需要),因此需要拆分。然后用strftime解析:我建议使用^{} 模块。可以将日期字符串转换为python
datetime
对象,然后使用该对象输出重新格式化的版本。在相关问题 更多 >
编程相关推荐