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?

Recommended Answers

All 3 Replies

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.

thanks I'll try that

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.