简体   繁体   English

如何使用Python在ISO中格式化日期?

[英]How can I format date in ISO using Python?

I have some dates which format is d/m/yyyy (eg 2/28/1987). 我有一些日期格式是d/m/yyyy (例如2/28/1987)。 I would like to have it in the ISO format : 1987-02-28 我想以ISO格式:1987-02-28

I think we can do it that way, but it seems a little heavy: 我想我们可以这样做,但似乎有点沉重:

str_date = '2/28/1987'
arr_str = re.split('/', str_date)
iso_date = arr_str[2]+'-'+arr_str[0][:2]+'-'+arr_str[1]

Is there another way to do it with Python? 有没有其他方法可以用Python做到这一点?

You could use the datetime module : 您可以使用datetime模块

datetime.datetime.strptime(str_date, '%m/%d/%Y').date().isoformat()

or, as running code: 或者,作为运行代码:

>>> import datetime
>>> str_date = '2/28/1987'
>>> datetime.datetime.strptime(str_date, '%m/%d/%Y').date().isoformat()
'1987-02-28'

I would use the datetime module to parse it: 我会使用datetime模块来解析它:

>>> from datetime import datetime
>>> date = datetime.strptime('2/28/1987', '%m/%d/%Y')
>>> date.strftime('%Y-%m-%d')
'1987-02-28'

What you have is very nearly how I would write it, the only major improvement I can suggest is using plain old split instead of re.split , since you do not need a regular expression: 你所拥有的几乎就是我如何编写它,我可以建议的唯一主要改进是使用普通的旧split而不是re.split ,因为你不需要正则表达式:

arr_str = str_date.split('/')

If you needed to do anything more complicated like that I would recommend time.strftime , but that's significantly more expensive than string bashing. 如果你需要做更复杂的事情,我会推荐time.strftime ,但这比字符串抨击贵得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM