【问题标题】:Most efficient way to convert datetime string (Jul 25, 2016 11:51:32 PM) into another string (YYYYMMDD) in python在 python 中将日期时间字符串(2016 年 7 月 25 日 11:51:32 PM)转换为另一个字符串(YYYYMMDD)的最有效方法
【发布时间】:2016-07-25 16:04:51
【问题描述】:

我有一个代表日期时间的字符串,例如: “2016 年 7 月 19 日下午 4:45:57”

我想将其转换为以下字符串:“20160725”

在 python 中最有效的方法是什么?

谢谢:)

注意:我需要这样做以便稍后将此日期输入到 csv 文件中,该文件将用于显示折线图。

【问题讨论】:

    标签: python string date datetime


    【解决方案1】:

    您可以使用datetime 模块的strptimestrftime 方法。以下是您想要的:

    from datetime import datetime as dt
    
    s = "July 25, 2016 - 11:51:32 PM"
    old_format = '%B %d, %Y - %H:%M:%S %p'
    new_format = '%Y%m%d'
    r = dt.strptime(s, old_format).strftime(new_format)
    print(r)
    # '20160725'
    

    【讨论】:

    • 感谢您的帮助。但是,这会返回以下内容:ValueError: time data 'Jul 19, 2016 4:45:57 PM' does not match format '%B %d, %Y - %H:%M:%S'
    • 但是您意识到有一个额外的'PM' 与您最初发布的不同?
    • 哦,谢谢你的评论!我没有注意到 pm :) 这是真的
    • 我已经更新了我的答案。以格式添加%p 可以解决此问题。还有那个连字符,你的原始数据中有吗?
    • 对于那些在谷歌上搜索的人,如果您处理的是一个完整的月份(例如:7 月),请使用 %B,如果您处理的是缩写(例如:Jul),请使用 %b。 tutorialspoint.com/python/time_strptime.htm
    猜你喜欢
    • 2013-06-28
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 2012-01-02
    • 2012-02-18
    • 1970-01-01
    相关资源
    最近更新 更多