python小菜 2009-01-21 18:00 采纳率: 0%
浏览 794
已采纳

将字符串转换为日期时间

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条回答 默认 最新

  • elliott.david 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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog