开发者

python: need help to implement strptime() the right way

I am trying to find the difference in days between the current date and the date that I extract from the database (postgresql)

This is my code:

    cur.execute('select id, city_id, event_id,开发者_开发百科 duration, DATE(startdate) from main_cityevent where DATE(startdate) <= DATE(NOW())')
    rows = cur.fetchall()
    for city_event in rows:
            startdate = str(city_event[4])
            sd = datetime.strptime(startdate, "%Y-%m-%d")
            diff = datetime.datetime.now() - sd

the last command (diff = datetime.datetime.now() - sd) gives me an AttributeError.

What am I doing wrong?


You are probably importing datetime.datetime (the class) instead of datetime (the module).

By always importing the datetime module, you can use both datetime.datetime and datetime.date, which is more appropriate in your case, and has a nice .today() method.

And you don't need the whole str() -> strptime() trip, since it should already be a python date object.

Also, you can subtract the dates within the query and get the difference in days:

postgres=# select '2011-07-05'::date - current_date;
 ?column? 
----------
       59
(1 row)

So your query would be something like

SELECT id, city_id, event_id, duration, DATE(startdate)-CURRENT_DATETIME AS days FROM main_cityevent WHERE DATE(startdate) <= DATE(NOW())

For a full description of postgres date/time functions, see here

On a related note, why do you need to cast 'startdate' inside the query? Are storing it as a string, or a timestamp, or something different? If it's a date, it should be treated as such. Types are important in RDBMS, for correctness and performance. You can (at the very least) have off-by-one errors by subtracting dates and datetimes.


As DiggyF alluded, you should use

diff = datetime.now() - sd

In the code above, the datetime.timedelta object named diff will have microseconds resolution. Unless you intended on microsecond resolution, handling the resultant timedelta may be harder than doing this

from datetime import date
tmp = startdate.split('-')
sd = date(int(tmp[0]), int(tmp[1]), int(tmp[2]))
diff = date.today() - sd

That yields a datetime.timedelta with day resolution...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜