简体   繁体   English

使用正则表达式提取时间

[英]Extract time using regex

I have scraped some data from the yellow pages using scrapy.我已经使用 scrapy 从黄页中抓取了一些数据。

The hours of the business provided from scraping are in a 12-hour format and I need to convert it into 24 hours.抓取提供的营业时间为 12 小时制,我需要将其转换为 24 小时制。

The format for the business hours I scraped are:我抓取的营业时间格式为:

Mon - Fri:,10:00 am - 7:00 pm.

I need to extract the two values for opening and closing time, convert them both into 24-hour format and then concatenate the string back together again.我需要提取打开和关闭时间的两个值,将它们都转换为 24 小时格式,然后再次将字符串连接在一起。

As a result, I need to devise a regex that will extract the time and then change it into a 24 hour format.因此,我需要 devise 一个正则表达式,它将提取时间,然后将其更改为 24 小时格式。 The final string should (as per previous example) should be:最后的字符串应该(根据前面的例子)应该是:

Mon - Fri:,10:00 - 19:00

I have tried different regex.我尝试了不同的正则表达式。 I tried the following:我尝试了以下方法:

import re

txt = 'Mon - Fri:,10:00 am - 7:00 pm'
data = re.findall(r'\s(\d{2}\:\d{2}\s?(?:AM|PM|am|pm))', txt)
print(data)

i am not python developer but we can in this way in javascript.我不是 python 开发人员,但我们可以通过这种方式在 javascript 中使用。 you can convert logic into python您可以将逻辑转换为 python

in this way you can convert this time to miltary time (24 hour)通过这种方式,您可以将此时间转换为军事时间(24 小时)

https://jsfiddle.net/1hxojLdf/2/ https://jsfiddle.net/1hxojLdf/2/

let text='Mon - Fri:,10:00 am - 7:00 pm';
const regex=/(\w+\s-\s\w+:.)(\d{1,2}:\d{1,2}\s(am|pm))\s-\s(\d{1,2}:\d{1,2}\s(am|pm))/;
const result=text.match(regex);
let timeone=result[2];
let timetwo=result[4];
timeone= moment(timeone,"h:mm A").format('HH:mm');
timetwo= moment(timetwo,"h:mm A").format('HH:mm');

text=result[1]+timeone+"-"+timetwo;
alert(text)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM