0

I am having a problem reading a date format in a file I am trying to count the difference between two dates. the format I have is 010108.


I tried to break up the date mmddyy but have run into other errors.

import datetime as dt

# US format month/day/year
#dateStr1 = '7/14/2006'
#dateStr2 = '5/1/2007'


mm1 = 01
dd1 = 01
yy1 = 08
mm2 = 03
dd2 = 12
yy2 = 08
dateStr1 = mm1 + '/' + dd1 + '/' + yy1 
dateStr2 = mm2 + '/' + dd2 + '/' + yy2


m1, d1, y1 = (int(x) for x in dateStr1.split('/'))
m2, d2, y2 = (int(x) for x in dateStr2.split('/'))

date1 = dt.date(y1, m1, d1)
date2 = dt.date(y2, m2, d2)

dateDiff = date2 - date1
print 'Difference in days = %d' % dateDiff.days

The file I am reading is a Unix output text file but other files are flopping the date format

any ideas?

2
Contributors
3
Replies
5
Views
9 Years
Discussion Span
Last Post by vegaseat
0

First of all, let me welcome you to the DaniWeb Python forum!

In your code you are almost there, but you can only concatenate strings ...

import datetime as dt

# US format month/day/year
#dateStr1 = '7/14/2006'
#dateStr2 = '5/1/2007'

mm1 = '01'  # need to be strings
dd1 = '01'
yy1 = '08'

mm2 = '03'
dd2 = '12'
yy2 = '08'

dateStr1 = mm1 + '/' + dd1 + '/' + yy1
dateStr2 = mm2 + '/' + dd2 + '/' + yy2

# test ...
print dateStr1, dateStr2

m1, d1, y1 = (int(x) for x in dateStr1.split('/'))
m2, d2, y2 = (int(x) for x in dateStr2.split('/'))

date1 = dt.date(y1, m1, d1)
date2 = dt.date(y2, m2, d2)

dateDiff = date2 - date1
print 'Difference in days = %d' % dateDiff.days

Please use the [code=python] and [/code] tag pair to enclose your python code.

0

The easiest way to extract mm, dd, yy from the 'mmddyy' date string is with slicing ...

# extract mm, dd, yy from a 'mmddyy' date string

import datetime as dt

def date_slice(s):
    """
    slices a date string of form mmddyy
    and returns int value tuple (mm, dd, yy)
    """
    return int(s[0:2]), int(s[2:4]), int(s[4:6])

dt1 = '010108'
dt2 = '031208'

m1, d1, y1 = date_slice(dt1)
m2, d2, y2 = date_slice(dt2)

# test ...
print m1, d1, y1, '   ', m2, d2, y2

# apply ...
date1 = dt.date(y1, m1, d1)
date2 = dt.date(y2, m2, d2)

dateDiff = date2 - date1
print 'Difference in days = %d' % dateDiff.days

You just got me interested since I use the 'mmddyy' a lot at the end of my filenames. If your years span the century mark, you need to add some extra intelligence.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.