【问题标题】:How to replace or remove the clock time?如何更换或删除时钟时间?
【发布时间】:2019-08-05 06:35:49
【问题描述】:

我有一个网络爬虫,我正在尝试从 DateTime 中删除时钟时间。例如,从爬虫中我得到“2019 年 1 月 29 日 09:46:46”,如何删除或替换“9:46:46”以便只剩下“2019 年 1 月 29 日”。

我尝试编写此代码,但没有任何结果。我使用 ".replace(time, ' ')" 删除小时、分钟和秒。但它看起来像删除所有的日期时间。

date_time = record.find('i').replace(time, '')

从 date_time 我根据我抓取的网站上的日期获得日期。但我希望只得到日期、月份和年份,而没有小时、分钟和秒。

【问题讨论】:

    标签: python-3.x datetime


    【解决方案1】:

    也许试试这个:

    import re
    text = "29 january 2019 09:46:46"
    justDate = re.split('\s\d{0,2}:\d{0,2}:\d{0,2}', text)[0]
    

    输出:

    justDate
    Out[60]: '29 january 2019'
    

    编辑:

    OP 还询问了如何获取字符串的时间部分。这样做:

    justTime =  re.split('\d{4}\s', text)[1] 
    

    输出:

    justTime
    Out[61]: '09:46:46'
    

    【讨论】:

    • 它有效,谢谢,但如果我只想要时间呢?
    • 然后你可以这样做:re.split('\d{4}\s', text)[1]
    • 我明白了,我以前不知道这些功能
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    相关资源
    最近更新 更多