我需要从字符串返回日期格式。目前我使用解析器将字符串解析为日期,然后用yyyy或yy替换年份。同样适用于其他日期项目。当我发送12-05-2018时,是否有一些我可以使用的功能会返回mm-dd-yyyy?
从技术上讲,这是一个不可能的问题。如果您在12-05-2018发送,我无法知道您是否发送了mm-dd-yyyy(2018年12月5日)或dd-mm-yyyy(2018年5月12日)。
一种方法可能是对符合预期日期模式的任何内容进行正则表达式替换,例如:
date = "Here is a date: 12-05-2018 and here is another one: 10-31-2010"
date_masked = re.sub(r'\b\d{2}-\d{2}-\d{4}\b', 'mm-dd-yyyy', date)
print(date)
print(date_masked)
Here is a date: 12-05-2018 and here is another one: 10-31-2010
Here is a date: mm-dd-yyyy and here is another one: mm-dd-yyyy
当然,上面的脚本不会检查日期是否真正有效。如果需要,可以使用Python中提供的日期库之一。
我真的不明白你打算用这种格式做什么。我可以想到你可能想要它的原因有两个。 (1)您希望在将来的某个时刻将标准化的datetime
转换回原始字符串。如果这就是你想要的那么你最好只存储标准化的datetime
和原始字符串。或者(2)你想得出关于发送数据的人的(狡猾)结论,因为不同的国籍将倾向于使用不同的格式。但是,无论你想要什么,你都可以这样做:
from dateutil import parser
def get_date_format(date_input):
date = parser.parse(date_input)
for date_format in ("%m-%d-%Y", "%d-%m-%Y", "%Y-%m-%d"):
# You can extend the list above to include formats with %y in addition to %Y, etc, etc
if date.strftime(date_format) == date_input:
return date_format
>>> date_input = "12-05-2018"
>>> get_date_format(date_input)
'%m-%d-%Y'
您在评论中提到您准备对12-05-2018(可能是5月或12月)和05-12-18(可能是2018年或2005年)这样的模糊日期做出假设。你可以将这些假设传递给dateutil.parser.parse
。它接受布尔关键字参数dayfirst
和yearfirst
,它将在不明确的情况下使用。
看一下datetime库。在那里你会发现函数strptime(),这正是你正在寻找的。
这是文档:https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior