【问题标题】:Extact date from string "3d02h"从字符串“3d02h”中提取日期
【发布时间】:2019-09-04 16:46:39
【问题描述】:

我正在从 SSH 连接输出中提取一个字符串,这给了我一个类似 '3d02h' 的字符串,我必须将此日期插入到数据库中。

输出来自在 cisco_switch 中执行的命令“show spanning-tree detail | inc ieee|occurr|from|is exec”,它给了我以下输出:

VLAN0001 正在执行 ieee 兼容的生成树协议 拓扑更改次数 490 上次更改发生在 3d02 小时前 来自 GigabitEthernet1/0/11

所以我使用 .split() 函数从输出中提取“3d02h”。

现在我想将字符串转换为日期时间对象。

我尝试使用 datetime.strptime(string, "%d %H") 从字符串中提取日期和小时,但它不起作用。

【问题讨论】:

  • 您忘记了图案中的字母。试试%dd%Hh
  • 但这不是日期,而是时间段。
  • "%d %H" 该模式在数字之间有一个空格,而您的源字符串没有。此外,您的源字符串在一天之后有字母 d,而您的模式没有。
  • 天数可能是可选的,如果时间段小于 1 天。
  • 我正在尝试将 '3d02h' 前转换为 datetime 对象,指示日历中它发生的日期(如 datetime(2019, 09, 1, 23, 55, 59))

标签: python datetime strptime


【解决方案1】:

我已经用 re 和 parsedatetime 完成了。

from datetime import datetime
import parsedatetime as pdt
import re
cal = pdt.Calendar()
print(datetime.now())
date = "3d02h"
index = 2
date = re.findall(r'[A-Za-z]+|\d+', date)
date_len = int(len(date))
date_len = date_len // 2
for item in range(0, date_len):
    date.insert(index, ' ago ')
    index += 3
date = "".join(date)
print(date)
date, flags = cal.parseDT(date)
assert flags
print(date)

输出是:

2019-09-05 13:37:28.710065
3d ago 02h ago 
2019-09-02 11:37:28

【讨论】:

    【解决方案2】:

    问题:一个时期之前的日期

    from datetime import datetime, timedelta
    import re
    
    dayshour = "3d02h"
    now = datetime.strptime('2019-09-05 13:37:28.710065', 
                            '%Y-%m-%d %H:%M:%S.%f')
    
    days, hours, _ = re.split(r'[dh]', dayshour)
    
    ago = now - timedelta(days=int(days), hours=int(hours))
    
    print('now:{}\n{} => {}, {}\nago:{}'\
          .format(now, dayshour, int(days), int(hours), 
                  ago.strftime('%Y-%m-%d %H:%M:%S')))
    

    输出

    now:2019-09-05 13:37:28.710065
    3d02h => 3, 2
    ago:2019-09-02 11:37:28
    

    用 Python 测试:3.6

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-17
      • 2020-08-14
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多