Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/hadoop/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中从字符串值中提取特定内容_Python - Fatal编程技术网

如何在python中从字符串值中提取特定内容

如何在python中从字符串值中提取特定内容,python,Python,我是python新手。我试图从字符串中提取日期和时间值 字符串值: List = ['D:/Python/sfusd_to_hipSfusd/reports_api/meet/activity/dt=2020-10- 02/api_batch_id=00db1d37-96bb-4beb-a8db-0e62443f5d81/2020-10-02 13-34-55.json'] 我需要的输出: 2020-10-02 13-34-55 有人能帮我用python解决这个问题吗?当然,我不知道要从

我是python新手。我试图从字符串中提取日期和时间值

字符串值:

List = ['D:/Python/sfusd_to_hipSfusd/reports_api/meet/activity/dt=2020-10- 
02/api_batch_id=00db1d37-96bb-4beb-a8db-0e62443f5d81/2020-10-02 13-34-55.json']
我需要的输出:

2020-10-02 13-34-55


有人能帮我用python解决这个问题吗?

当然,我不知道要从中提取日期的字符串的格式。但对于如何做到这一点,这是一个粗略的想法。请注意,索引
-1
是最后一个位置,或者相当于从右侧开始的第一个位置

s =  'D:/Python/sfusd_to_hipSfusd/reports_api/meet/activity/dt=2020-10-02/api_batch_id=00db1d37-96bb-4beb-a8db-0e62443f5d81/2020-10-02 13-34-55.json'
parts_split_by_slash = s.split("/")
after_last_slash = parts_split_by_slash[-1]
part_before_dot = after_last_slash.split(".")[0]
print(part_before_dot)
用于获得正确的图案

import re
re.findall("([0-9]{4}\-[0-9]{2}\-[0-9]{2} [0-9]{2}-[0-9]{2}-[0-9]{2})", s)
输出:

['2020-10-02 13-34-55']

您可以使用
os.path.basename
获取文件名。然后需要使用
os.path.splitext
将扩展名和文件名分开

代码:


因为您的字符串似乎是路径值

您还可以利用


欢迎来到Stackoverflow。请向我们展示您尝试过的内容,并适当设置您的问题格式(即使代码显示为代码)。@Sakthi:请接受答案:
import os

string_value = ["D:/Python/sfusd_to_hipSfusd/reports_api/meet/activity/dt=2020-10- 02/api_batch_id=00db1d37-96bb-4beb-a8db-0e62443f5d81/2020-10-02 13-34-55.json"]
for str in string_value:
    file = os.path.basename(string_value[0])
    f_name, f_ext = os.path.splitext(file)
    print(f_name)

>>> s =  'D:/Python/sfusd_to_hipSfusd/reports_api/meet/activity/dt=2020-10-02/api_batch_id=00db1d37-96bb-4beb-a8db-0e62443f5d81/2020-10-02 13-34-55.json'

>>> os.path.splitext(os.path.split(s)[1])[0]
'2020-10-02 13-34-55'
>>>