Python日志记录时间戳转换为mysql时间戳

2024-09-29 17:22:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个巨大的日志文件,时间戳格式如下:

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()

Tags: 文件csv函数infomainsysline时间
3条回答

{{cd2>要重新格式化{cd2>,然后使用}?在

import time

input_format = "%m/%d/%Y %I:%M:%S %p INFO" # or %d/%m...
output_format = "%Y-%m-%d %H:%M:%S"

def convert_time(logging_time):
    return time.strftime(output_format, time.strptime(logging_time, input_format))

print convert_time("08/07/2013 11:40:08 PM INFO")
# prints 2013-08-07 23:40:08

但是请注意,strptimestrftime可能受当前区域设置的影响,您可能需要将区域设置为C(它也由datetime模块内部使用),因为{}可以为不同的区域设置AM/PM的不同格式;因此为了安全起见,您可能需要在开始时运行以下代码:

^{pr2}$

按照建议,用如下的strptime转换它:

converter="%d/%m/%Y %H:%M:%S %p INFO"
result = dt.datetime.strptime("08/07/2013 11:40:08 PM INFO",converter)

由于“INFO”字符串(编辑:不需要),因此需要拆分。然后用strftime解析:

^{pr2}$

我建议使用^{}模块。可以将日期字符串转换为python datetime对象,然后使用该对象输出重新格式化的版本。在

from datetime import datetime

mysqltime = "2013-04-11 13:18:02"
timeobj = datetime.strptime(mysqltime, "%Y-%m-%d %H:%M:%S")
loggingtime = timeobj.strftime("%m/%d/%Y %H:%M:%S %p")

相关问题 更多 >

    热门问题