Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.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
如何将日期字符串(例如';2020年1月3日';)格式更改为';年月日';python代码中的格式_Python_Regex_Datetime - Fatal编程技术网

如何将日期字符串(例如';2020年1月3日';)格式更改为';年月日';python代码中的格式

如何将日期字符串(例如';2020年1月3日';)格式更改为';年月日';python代码中的格式,python,regex,datetime,Python,Regex,Datetime,一个文件夹中有多个文本文件,需要编写一个python代码来读取所有文本文件,并在此位之后提取日期字段 来自每个文本文件的文本“$published_date:”(例如,published_date:2020年1月2日) 所有文件如下所示:- $Publisher_Name: ABC Corp. $Publisher_Date: January 02 2020.

一个文件夹中有多个文本文件,需要编写一个python代码来读取所有文本文件,并在此位之后提取日期字段 来自每个文本文件的文本“$published_date:”(例如,published_date:2020年1月2日)

所有文件如下所示:-

    $Publisher_Name: ABC Corp.                                                            
    $Publisher_Date: January 02 2020.                                                                 
    This copy was authored by xyz.
    
文件由几行组成,并在每个文件的某处打印“”$Publisher\u Date:“”

需要帮助将以下代码中的日期格式从日期字符串(例如“2020年1月3日”)更改为“dd/mm/yyyy”

这是python代码,我试图从basepath读取文本文件,并在这段文本“published_date:”后提取日期值

希望在我想要的输出中摆脱路径位置和更改的日期格式

    **My Desired output is** 
    
    test2.txt    03/01/2020
    test3.txt    23/01/2021
    test4.txt    15/03/2019

使用
strftime
首先转换为datetime对象,然后使用
strftime
转换回所需格式的字符串

从日期时间导入日期时间
def f(fn):
以开放式(fn)作为f:
对于f中的s:
#获取发布者日期并转换为所需格式
m=重新搜索(r'\b发布者日期:(\w+\d{2}\d{4}),s)
如果m:
dt=datetime.strtime(m.group(1),“%B%d%Y”)
dt_out=dt.strftime(“%d/%m/%Y”)
返回(fn,dt_输出)
其他:
返回None#文件中没有匹配项

您使用的python版本是什么?
    path\tes2.txt', 'January 03 2020'
    path\tes3.txt', 'January 23 2021'
    **My Desired output is** 
    
    test2.txt    03/01/2020
    test3.txt    23/01/2021
    test4.txt    15/03/2019