[Last Call] Learn how to a build a cloud-first strategyRegister Now


Formatting datetime objects in python 2.4

Posted on 2011-05-07
Medium Priority
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 = user3@website.com
network_url = http://web-stations.org

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 = datetime.now(pytz.timezone('America/Anchorage'))
            #current_date = datetime.now() #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
  • 3
LVL 13

Accepted Solution

Superdave earned 1500 total points
ID: 35713575
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

ID: 35713977
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

ID: 35724176
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

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

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction On September 29, 2012, the Python 3.3.0 was released; nothing extremely unexpected,  yet another, better version of Python. But, if you work in Microsoft Windows, you should notice that the Python Launcher for Windows was introduced wi…
Dictionaries contain key:value pairs. Which means a collection of tuples with an attribute name and an assigned value to it. The semicolon present in between each key and values and attribute with values are delimited with a comma.  In python we can…
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 modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
Suggested Courses
Course of the Month18 days, 12 hours left to enroll

834 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