更改字符串的时间格式 [英] change time format for a string
问题描述
我想写一个函数来改变时间格式,用一个偏移量来移动日期
I want to write a function to change the time format and an offset is used to shift the date
例如,我有一个字符串
"this is a string 2012-04-12 23:55 with a 2013-09-12 timezone"
我想把它改成类似
"**this is a string 20-Apr-2012 13:40 with a 19-Sep-2013 timezone**"
即数据的格式从yyyy-mm-dd
变为dd-bbb-yyyy
,日期偏移了.
That is, the format of the data change from yyyy-mm-dd
to dd-bbb-yyyy
and the date is shifted by offset.
我编写了以下函数,但它只给出这是一个字符串 20-Jun-2012 13:40,时区为 2013-11-12"
I write the following function but it only gives "this is a string 20-Jun-2012 13:40 with a 2013-11-12 timezone"
import re
import time
import datetime
def _deIDReportDate(report, offset=654321):
redate = re.compile(r"""([0-9]+-[0-9]+-[0-9]+\s+[0-9]+:[0-9]+)|([0-9]+-[0-9]+-[0-9]+)""")
match = redate.search(report)
for match in redate.finditer(report):
dt = match.group()
if len(dt) > 10:
dt = datetime.datetime.strptime(dt, '%Y-%m-%d %H:%M')
dt += datetime.timedelta(seconds=offset)
new_time = dt.strftime('%d-%b-%Y %H:%M')
newReport = report[:match.start()] + new_time + report[match.end():]
return newReport
else:
dt = datetime.datetime.strptime(dt, '%Y-%m-%d')
dt += datetime.timedelta(seconds=offset)
new_time = dt.strftime('%d-%b-%Y')
newReport = report[:match.start()] + new_time + report[match.end():]
return newReport
谁能帮助修复/改进我的代码?
Can anyone help to fix/improve my code?
推荐答案
你的错误是由于你试图调用 report.groups()
;您从未在 report
参数上应用正则表达式.
Your error is caused by you trying to call report.groups()
; you never applied the regular expression on the report
parameter.
您的代码可以显着简化:
Your code can be simplified significantly:
_dt = re.compile(r"""
[12]\d{3}- # Year (1xxx or 2xxx),
[0-1]\d- # month (0x, 1x or 2x)
[0-3]\d # day (0x, 1x, 2x or 3x)
(?:\s # optional: time after a space
[0-2]\d: # Hour (0x, 1x or 2x)
[0-5]\d # Minute (0x though to 5x)
)?
""", flags=re.VERBOSE)
def _deIDReportDate(report, offset=654321):
def replace(match):
dt = match.group()
if len(dt) > 10:
# with time
dt = datetime.datetime.strptime(dt, '%Y-%m-%d %H:%M')
dt += datetime.timedelta(seconds=offset)
return dt.strftime('%d-%b-%Y %H:%M')
dt = datetime.datetime.strptime(dt, '%Y-%m-%d')
dt += datetime.timedelta(seconds=offset)
return dt.strftime('%d-%b-%Y')
return _dt.sub(replace, report)
replace
嵌套函数为输入字符串中的每个非重叠匹配项调用.
The replace
nested function is called for each non-overlapping match in the input string.
这篇关于更改字符串的时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!