我在列表中有多个字符串,例如/Date(-31431600000)/
我正在尝试提取包含减号的数字并将其转回日期。该字符串代表一个Linux EPOCH日期
我试过了:
import datetime as dt
date_list = ["/Date(-31431600000)/", "/Date(-31431600000)/"]
[dt.datetime.fromtimestamp(int(filter(lambda x: x.isdigit(), y)) / 1000) for y in date_list]`
但它错过了减号。
谢谢!
答案 0 :(得分:2)
尝试使用以下正则表达式:
(?<=Date\()-\d+(?=\))
请参阅regex demo
python (demo)
import re
regex = r"(?<=Date\()-\d+(?=\))"
str = "/Date(-31431600000)/"
matches = re.finditer(regex, str)
for matchNum, match in enumerate(matches):
matchNum = matchNum + 1
print ("{match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group())) # -31431600000
答案 1 :(得分:2)
我认为最安全的正则表达式是:
/Date(
此处您还会检查它是以)/
开头,以>>> import re
>>> rgx=re.compile(r'(?:/Date\()(-?\d+)(?:\)/)')
>>> rgx.match("/Date(-31431600000)/").group(1)
'-31431600000'
结尾,前面只有一个可选的减号。然后,您可以使用以下方式获取日期:
int
因此是一个字符串,您可以使用int(..)
转换为>>> int(rgx.match("/Date(-31431600000)/").group(1))
-31431600000
:
@Test
public void createNewShopAndCheckUserShopsCollection()
{
//given
ShopEntity shop = new ShopEntity();
String shopName = "test shop";
MallEntity mall = new MallEntity();
mall.setId(1L);
UserEntity user = userService.findOne(1L);
int shopsModeratedBefore = user.getModeratedShops().size();
shop.setMall(mall);
shop.setName(shopName);
shop.setModerators(Collections.singletonList(user));
ShopEntity savedShop = shopRepository.save(shop);
user = userService.findOne(1L);
assertThat(user.getModeratedShops()).hasSize(shopsModeratedBefore + 1);
}
答案 2 :(得分:1)
r'[^-0-9]'
删除除-
和0-9
位数以外的所有字符。
[re.sub(r'[^-0-9]','',x) for x in date_list]