Converting string into datetime

Short and simple. I've got a huge list of date-times like this as strings:

Jun 1 2005  1:33PM
Aug 28 1999 12:00AM

I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects.

Any help (even if it's just a kick in the right direction) would be appreciated.

Edit: This is going through Django's ORM so I can't use SQL to do the conversion on insert.


datetime.strptime is the main routine for parsing strings into datetimes. It can handle all sorts of formats, with the format determined by a format string you give it:

from datetime import datetime

datetime_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

The resulting datetime object is timezone-naive.

Links:

  • Python documentation for strptime : Python 2, Python 3

  • Python documentation for strptime / strftime format strings: Python 2, Python 3

  • strftime.org is also a really nice reference for strftime

  • Notes:

  • strptime = "string parse time"
  • strftime = "string format time"
  • Pronounce it out loud today & you won't have to search for it again in 6 months.

  • Use the third party dateutil library:

    from dateutil import parser
    dt = parser.parse("Aug 28 1999 12:00AM")
    

    It can handle most date formats, including the one you need to parse. It's more convenient than strptime as it can guess the correct format most of the time.

    It very useful for writing tests, where readability is more important than performance.

    You can install it with:

    pip install python-dateutil
    

    Check out strptime in the time module. It is the inverse of strftime.

    $ python
    >>> import time
    >>> time.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')
    time.struct_time(tm_year=2005, tm_mon=6, tm_mday=1,
                     tm_hour=13, tm_min=33, tm_sec=0,
                     tm_wday=2, tm_yday=152, tm_isdst=-1)
    
    链接地址: http://www.djcxy.com/p/4266.html

    上一篇: 将Unix时间戳转换为JavaScript中的时间

    下一篇: 将字符串转换为日期时间