简体   繁体   English

仅在python中转换时间

[英]Converting only time in python

I'm working with lines of text in a csv file similar to this: 我正在使用类似于以下内容的csv文件中的文本行:

 2012-03-16     13:47:31.915    -0400       image

I want to be able to run a for loop through the csv file, and subtract just the time in between each line of code. 我希望能够在csv文件中运行一个for循环,并减去每一行代码之间的时间。 Currently, I can only do it through the date and time, but it's causing some confusion. 目前,我只能在日期和时间上做到这一点,但这引起了一些混乱。 This what I have now. 这就是我现在所拥有的。

    newLogFile = csv.reader(open('newLogFile.csv', 'r+'), delimiter="\t")
    row_count = sum(1 for row in csv.reader( open('newLogFile.csv') ) )
    fmt = '%Y-%m-%d %H:%M:%S.%f'


    for row in newLogFile:
      time = (row[0] + " " + row[1])


      ts1 = datetime.datetime.strptime(time, fmt)

      row_count+=1
      if row_count == 33:
         current = ts1
         current = ts1 - current

      print ("%s - %s" %(ts1,current))
      current = ts1 - current
      print current

The output looks something like this: 输出看起来像这样:

    2012-03-16 13:52:09.462000 - 0:01:44.866000
    2012-03-16 13:50:24.596000

I tried looking through the datetime and time modules but I couldn't find anything that would have worked. 我尝试查看日期时间和时间模块,但找不到任何可行的方法。 I know there is something wrong in the subtraction as well, but I want to get the conversion correct first. 我知道减法也有问题,但我想先正确进行转换。

Thanks for the help 谢谢您的帮助

UPDATE: 更新:

I figured out my problem... 我发现了我的问题...

newLogFile = csv.reader(open('newLogFile.csv', 'r+'), delimiter="\t")

fmt = '%Y-%m-%d %H:%M:%S.%f'
row_count = 0

for row in newLogFile:
    time = (row[0] + " " + row[1])
    timestamp = strptime(time, fmt)
    current_value = mktime(timestamp)

    row_count+=1
    if row_count == 1:
        previous_value = current_value

    print ("%s - %s" %(current_value, previous_value))
    total_value = current_value - previous_value
    print total_value

    previous_value = current_value

I decided to set the time to seconds to find out a more exact and reliable value. 我决定将时间设置为几秒钟,以找到更准确和可靠的值。 I also fixed my subtraction as well, by changing the row_count and reseting the previous_value to the current_value before ending the for loop 在结束for循环之前,我还通过更改row_count并将先前的值重置为current_value来固定减法。

I figured out my issue, see the update under the original question. 我发现了问题,请参阅原始问题下的更新。

newLogFile = csv.reader(open('newLogFile.csv', 'r+'), delimiter="\t")

fmt = '%Y-%m-%d %H:%M:%S.%f'
row_count = 0

for row in newLogFile:
    time = (row[0] + " " + row[1])
    timestamp = strptime(time, fmt)
    current_value = mktime(timestamp)

    row_count+=1
    if row_count == 1:
        previous_value = current_value

    print ("%s - %s" %(current_value, previous_value))
    total_value = current_value - previous_value
    print total_value

    previous_value = current_value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM