Formatting datetime objects in python 2.4

Posted on 2011-05-07
Last Modified: 2012-06-21

I'm trying to format datetime objects read in from log files to evaluate the amount of time that has transpired since the latest reading in each log file. The script below works in python 2.5, but I'm getting errors on the python 2.4 platform that it will need to run on. The latest error is 'TypeError: function takes at most 8 arguments (9 given)', for this line:
ts = datetime(*time.strptime(last_ts, '%Y-%m-%d %H:%M:%S'))

I have reviewed the EE knowledge base and other sources on this subject and still don't understand the error.


base_dir = /home/user1/public_html/stations/
www_base = /stations/
template_file = /home/user2/cron/graphs/template.html
destination = /home/user2/public_html/stations/graphs.html
contact_address =
network_url =

stn1 = Station 1
stn2 = Station 2
stn3 = Station 3
etc. for 12 stations

Open in new window

import os
import sys
import time
from datetime import datetime, date, timedelta
import pytz
import ConfigParser
from configobj import ConfigObj

    cfg = sys.argv[1]
    print 'Error: pls include config file!'

parser = ConfigParser.SafeConfigParser()
destination = parser.get('Main', 'destination')
network_url = parser.get('Main', 'network_url')
source_dir = parser.get('Main', 'source_dir')
target = open(destination, 'w')

periods = ['2day', '7day', '14day', '1month', '2month', '4month', '6month', '9month', '12month']
period_map = { '7day': 7, '14day': 14, '1month': 30, '2month':60 , '4month': 120 , \
                         '6month': 180, '12month': 360 } 

def procIni():

    station_docs = []
    config = ConfigObj(cfg)

    for option in config['Stations']:
        diag_path = source_dir + option + '/' + option
        if option in [ 'stn1', 'stn2', 'stn3' ]:
            source = diag_path + '_HrlyDiag.dat'
        elif option == 'stn4':
            source = diag_path + '_Hourly.dat'
            source = diag_path + '_HourlyDiag.dat'

        if source:
            current_date ='America/Anchorage'))
            #current_date = #not v4-compliant
            seven = timedelta(days=7)          

            InDiag = open(source, 'r')
            line_list = InDiag.readlines()
            last_line = line_list[len(line_list)-1]
            last_ts = last_line[1:20]
            #ts = datetime.strptime(last_ts, '%Y-%m-%d %H:%M:%S') #for v2.5
            #datetime.datetime has no attribute 'strptime' in v2.4...
            ts = datetime(*time.strptime(last_ts, '%Y-%m-%d %H:%M:%S'))
            #TypeError: function takes at most 8 arguments (9 given)
            time_diff = current_date - ts

            station_docs.append( (option, ts, time_diff) )

    for stn, ts, time_diff in station_docs:
        if time_diff > seven:
            print stn, 'late', time_diff
            print stn, 'no delay'


Open in new window

Question by:sara_bellum
    LVL 13

    Accepted Solution

    I tried it with 2.7 and it gives the same error; funny that it would have worked in 2.5.
    After the first six items the lists don't seem to be the same, so it works if you do:

    ts = datetime(*time.strptime(last_ts, '%Y-%m-%d %H:%M:%S')[:6])


    Author Comment

    Thanks very much, it worked!

    For python 2.5, I had used this instead:
    ts = datetime.strptime(last_ts, '%Y-%m-%d %H:%M:%S')
    But the same line in version 4 returns this error:
    datetime.datetime has no attribute 'strptime'

    I find it confusing that the v.4 datetime module requires us to specify the length of the date string, but no matter.

    Now I have another problem, this time with line 56:
    time_diff = current_date - ts
    # TypeError: can't subtract offset-naive and offset-aware datetimes

    I tried a few things, which I copy here along with the errors they return:
    ts_offset = datetime(ts, tzinfo=pytz.timezone('America/Anchorage'))
    # TypeError: function takes at least 3 arguments (1 given)

    ts_offset = datetime(*time.strptime(ts, tzinfo=pytz.timezone('America/Anchorage')))
    #TypeError: strptime() takes no keyword arguments

    So as I understand it, I need to make the ts date object offset-aware to obtain a time difference, but I have no idea how to do that. I tried separating tzinfo out to avoid the need for a keyword argument -
    tzinfo = pytz.timezone('America/Anchorage')
    ts_offset = datetime(*time.strptime(ts, tzinfo)) # but the format is wrong -
    # TypeError: expected string or buffer

    What to do?


    Author Comment

    I found some code to fix the problem of subtracting offset-aware datetimes  in 2.4:

    (rYr, rMo, rDay, rHr, rMin, rSec) = time.strptime(last_ts, "%Y-%m-%d %H:%M:%S")[0:6]
    ts = datetime(rYr, rMo, rDay, rHr, rMin, rSec, tzinfo=pytz.timezone('America/Anchorage'))

    I don't quite follow how it works, but it does. I'll wait a bit for some words of wisdom and then close this  out, txs.


    Author Closing Comment

    I'm accustomed to a little more depth in the answers I get on EE :(

    Featured Post

    Highfive + Dolby Voice = No More Audio Complaints!

    Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

    Join & Write a Comment

    "The time has come," the Walrus said, "To talk of many things: Of sets--and lists--and dictionaries-- Of variable kinks-- And why you see it changing not-- And why so strange are strings." This part describes how variables and references (see …
    The purpose of this article is to demonstrate how we can use conditional statements using Python.
    Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
    Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now