Menu

struct_date into database?

Help
2005-10-10
2012-09-19
  • Peter Bowyer

    Peter Bowyer - 2005-10-10

    MySQLdb's datetime support is working great for me and it's cool not to have to worry about it.

    However, feedparser produces struct_time items which MySQLdb is not inserting into the database (the datetime column ends up filled with "0000-00-00 00:00:00")

    I can find a method to convert a datetime object to a struct_time but not the other way. What is the best way to handle struct_time structures with MySQLdb? I am using 1.2.0 final.

     
    • Andy Dustman

      Andy Dustman - 2005-10-10

      I don't know what format struct_time is in, but MySQL ultimately expects to see an ISO format timestamp, i.e. 2005-10-10Z16:05:09 (Z may be space).datetime objects and mx.DateTime objects have converters to do this automatically.

      Check out this page:

      http://64.233.187.104/search?q=cache:YwSLG70Jrp4J:www.asiatica.org/~ludo/downloads/feedsloader_threading.py+struct_time+feedparser&hl=en

      It looks like struct_time might be the n-tuple you get back from time.localtime() or time.gmtime(). So you can either use time.strftime() to produce a suitable string (as the code above does) or use it to make a datetime object, i.e.

      from datetime import datetime
      from time import mktime

      dt = datetime.fromtimestamp(mktime(struct_time))

      (mktime() needs the tuple to be local time)

       
      • Peter Bowyer

        Peter Bowyer - 2005-10-10

        struct_time is the n-tuple - it's documented on http://docs.python.org/lib/module-time.html, and according to the page in version 2.2: "The time value sequence was changed from a tuple to a struct_time, with the addition of attribute names for the fields."

        I am confused by all the different date/time modules in Python and the difference in handling them with MySQLdb (and in general - surely one date/time library in Python is enough?), but if strftime is what I need in this case then so be it.

        Thanks for your help!

         
        • Andy Dustman

          Andy Dustman - 2005-10-10

          time is a mostly low-level interface to the standard C library, and has been around forever. datetime is an object-oriented approach, which allows for easier data manipulation, and has only been around since Python-2.2, I think. mx.DateTime has been around for a long time (since at least Python-1.5) and essentially does what datetime does, but it's a third-party module.

           

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.