如何更改字符串中日期的日期格式?

时间:2017-09-12 11:46:38

标签: python python-3.x

我有一个字符串“你好,请将月份放在中间,从2017年4月24日起更改日期”

class Paragraph:

    @staticmethod
    def change_date_format(paragraph):
        return None

print(Paragraph.change_date_format('Hello please change the date from 04-24-2017 by putting month in the middle'))

我需要将此更改为“您好,请将月份放在中间,从2017年4月24日起更改日期”

2 个答案:

答案 0 :(得分:0)

import re
def change_date_format(paragraph):
    return re.sub('(\d+)/(\d+)/(\d+)', 
        lambda m: '{}/{}/{}'.format(m.group(2), m.group(1), m.group(3)), 
        paragraph)

这会找到由斜线分隔的三组数字序列(如04/27/2017),然后使用format交换第一组和第二组。

答案 1 :(得分:-1)

datetime可以这样做:

import datetime
def change_date_format(date):
        return datetime.datetime.strptime(date, '%m/%d/%Y').strftime('%d/%m/%Y')
相关问题