Pregunta

So, I have attempted this quite a few times; this has been my latest attempt:

import csv
import collections
import datetime

print "Please type file name to open:"
fileName = raw_input('> ')
print ""


incidents = collections.Counter()
with open(fileName) as input_file:
    for row in csv.reader(input_file, delimiter=','):       
        d0 = str(incidents[row[8]])
        d1 = str(incidents[row[7]])
        date0 = datetime.datetime.strptime(d0, "%Y/%m/%d %H:%M:%S").date()
        date1 = datetime.datetime.strptime(d1, "%Y/%m/%d %H:%M:%S").date()
        delta = (date0 - date1).days
        print delta

Essentially, I have a CSV file with two columns of data. Both are dates in this format: "1/21/2014 10:51 AM". I need to be able to take the difference of the dates and convert it into a decimal.

For instance if column 1, row 1 was "1/21/2014 10:51 AM" and column 2, row 1 was "9/4/2012 2:56:29 AM". Then the final output should be "504.33".

I can post other attempts/more in depth of an explanation if needed.

¿Fue útil?

Solución

Regarding the date you provided, one of those two format should work.

With seconds:

"%m/%d/%Y %I:%M:%S %p"

Without seconds:

"%m/%d/%Y %I:%M %p"

Read more about the strptime format behaviour here: Datetime documentation

It's well explained with samples of what it will parse.


For instance if column 1, row 1 was "1/21/2014 10:51 AM" and column 2, row 1 was "9/4/2012 2:56:29 AM". Then the final output should be "504.33".

According to this:

date0 = datetime.datetime.strptime(d0, "%m/%d/%Y %I:%M:%S %p")
date1 = datetime.datetime.strptime(d1, "%m/%d/%Y %I:%M %p")
delta = date0 - date1
return delta.days + (delta.seconds / 86400.0) # 60 seconds in 60 minutes in 24 hours

Otros consejos

Provided your datetime stamps are actually consistent (and are not missing the seconds, like in your "1/21/2014 10:51 AM" sample), then you need to use the correct format to parse the timestamps:

date0 = datetime.datetime.strptime(d0, '%m/%d/%Y %I:%M:%S %p')
date1 = datetime.datetime.strptime(d1, '%m/%d/%Y %I:%M:%S %p')
delta = date0 - date1
delta = delta.days + (delta.seconds / 86400.0)  # add day fraction
print delta
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top