替换字符串中的日期时间字符

时间:2018-02-18 11:51:57

标签: python string date replace

考虑以下日期str示例:

'20180101,20180102,20180103,20180104,20180105,20180106,20180107,20180108,20180109,20180110,20180111,20180112,20180113,20180114,20180115,20180116,20180117,20180118,20180119,20180120,20180121,20180122,20180123,20180124,20180125,20180126,20180127,20180128,20180129,20180130,20180131,20180201,20180202,20180203,20180204,20180205,20180206,20180207,20180208'

使用模块.replace('2018','2018-')中的re.sub('2018', '2018-', foo_string)re,日期更改为2018-0101。但是,我想在一系列日期中插入连字符。我试过以下re.sub('{}'.format(range(2018,2019)), '2018-', foo_string)无济于事。返回字符串时不做任何更改。作为参考,我想在1981年到2018年间使用连字符。

此外,我不确定如何以干净的方式在月份和日期之间插入连字符。非常感谢帮助这些方向。

5 个答案:

答案 0 :(得分:4)

我认为使用datetime会更加pythonic,

from datetime import datetime

date_list = '20180101,20180102,20180103,20180104,20180105,20180106,20180107,20180108'

def new_date_format(old_format_str):
    date_format = datetime.strptime(old_format_str, '%Y%m%d')
    new_format = date_format.strftime("%Y-%m-%d")
    return new_format

for date_str in date_list.split(","):
    print(new_date_format(date_str))

这将产生以下输出:

2018-01-01
2018-01-02
2018-01-03
2018-01-04
2018-01-05
2018-01-06
2018-01-07
2018-01-08

答案 1 :(得分:1)

我愿意

def insert_hyphen(stri):
    return ",".join([date[:4]+"-"+date[4:] for date in stri.split(',')])

如果你想要双连字符,那么

def insert_hyphen(stri):
    return ",".join([date[:4]+"-"+date[4:6]+"-"+date[6:] for date in stri.split(',')])

答案 2 :(得分:1)

如果您的列表包含日期,为什么不将您的列表存储为日期?

Python有一个datetime模块,它可以实现这个目的:

from datetime import datetime

lst = '20180101,20180102'

# first convert to datetime
lst = [datetime.strptime(i, '%Y%M%d') for i in lst.split(',')]

# define year combiner
def year_range(lst, year_start, year_end):
    return [i.replace(year=j) for j in range(year_start, year_end+1) for i in lst]

# make list for year range from lst
lst = year_range(lst, 2015, 2018)

# [datetime.datetime(2015, 1, 1, 0, 1),
#  datetime.datetime(2016, 1, 1, 0, 1),
#  datetime.datetime(2017, 1, 1, 0, 1),
#  datetime.datetime(2018, 1, 1, 0, 1),
#  datetime.datetime(2015, 1, 2, 0, 1),
#  datetime.datetime(2016, 1, 2, 0, 1),
#  datetime.datetime(2017, 1, 2, 0, 1),
#  datetime.datetime(2018, 1, 2, 0, 1)]

答案 3 :(得分:1)

如果您需要使用re模块,您只需匹配数字序列并将其替换为与连字符混合的内容:

import re

string = '20180101,20180102,20180103,20180104,20180105,20180106,20180107,20180108,20180109,20180110,20180111,20180112,20180113,20180114,20180115,20180116,20180117,20180118,20180119,20180120,20180121,20180122,20180123,20180124,20180125,20180126,20180127,20180128,20180129,20180130,20180131,20180201,20180202,20180203,20180204,20180205,20180206,20180207,20180208'

result = re.sub('([0-9]{4})([0-9]{2})([0-9]{2})','\\1-\\2-\\3',string,0)

print(result)

答案 4 :(得分:0)

使用此:

string = '20180203'
new_string = string[:4:] + '-' + string[4:6:] + '-' + string[6::]
print (new_string)

结果:

  

2018年2月3日

只需确保日期格式为YYYYMMDD。