954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Python - iterate hours between two values

Hi folks,


(Python 2.4.x - I cannot install any modules including dateutil)


Here's what I have so far.

mydate=['20111025.00', '20111026.12']

start_time= time.strptime(mydate[0], "%Y%m%d.%H")[:5]
end_time=time.strptime(mydate[1], "%Y%m%d.%H")[:5]

for myhour in datespan(time.strptime(mydate[0], "%Y%m%d.%H")[:4], time.strptime(mydate[1], "%Y%m%d.%H")[:4], delta=datetime.timedelta(hours=1)):
    print myhour


What I'm trying to do is take the two values in mydate list - and show all hours inbetween the two values given. in the above example it would (or should) show.

20111025.00
20111025.01
20111025.02
...
20111026.12

Problem with the above code is it tells me.

can only concatenate tuple (not "datetime.timedelta") to tuple


Just can't make heads or tails out of it. Any suggestions?

Thank you.

magnum_vf
Newbie Poster
3 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 

I seems to me that you add a datetime.timedelta of one hour to a datetime.datetime to get a new datetime.datetime.

Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

Grib means this:

import datetime

mydate=['20111025.00', '20111026.12']
fmt = "%Y%m%d.%H"
hour = datetime.timedelta(hours=1)

start_time,  end_time = [datetime.datetime.strptime(d, fmt) for d in mydate]

now = start_time
while now <= end_time:
    print now.strftime(fmt)
    now += hour


Doing this manually by normal loop is also not so tough job.

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

hmmmmm,

Now it's popping an error on me.

AttributeError: type object 'datetime.datetime' has no attribute 'strptime'


is datetime.strptime new in 2.5? I've got 2.4.x

magnum_vf
Newbie Poster
3 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 

http://stackoverflow.com/questions/5585706/datetime-datetime-strptime-not-present-in-python-2-4-1
See first answer for alternative:

datetime(*(time.strptime(date_string, format)[0:6]))
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

man geez finally.

I saw that too - read right the heck over it. Thanks for the splash of water to the face.

working code.

import datetime, time

mydate=['20111025.00', '20111026.12']
fmt = "%Y%m%d.%H"
hour = datetime.timedelta(hours=1)
start_time, end_time = [datetime.datetime(*(time.strptime(d, fmt)[0:6])) for d in mydate]

now = start_time
while now <= end_time:
    print now.strftime(fmt)
    now += hour
magnum_vf
Newbie Poster
3 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: