叼花硬汉 2009-01-21 18:00 采纳率: 0%
浏览 1772
已采纳

将字符串转换为日期时间

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.

转载于:https://stackoverflow.com/questions/466345/converting-string-into-datetime

  • 写回答

19条回答 默认 最新

  • 撒拉嘿哟木头 2009-01-21 18:08
    关注

    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:

    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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(18条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制