简体   繁体   English

在2014年1月4日给出时如何将mm / dd / yyyy格式转换为python 3.0中的yyyy-mm-dd

[英]How to convert from mm/dd/yyyy format to yyyy-mm-dd in python 3.0 when given 1/4/2014

So the I generally understand how I would convert from mm/dd/yyyy format to yyyy-mm-dd if the initial date given was something like 01/04/2014. 所以我一般都明白如果给出的初始日期是01/04/2014,我将如何从mm / dd / yyyy格式转换为yyyy-mm-dd。 However I am only given 1/4/2014 (without zeroes). 但是我只给了1/4/2014(没有零)。 Is there a clean and more efficient way of converting this in python 3 rather than writing a bunch of if statements? 有没有一种干净,更有效的方法在python 3中转换它而不是写一堆if语句?

>>> from datetime import datetime
>>> date = datetime.strptime("1/4/2014", "%m/%d/%Y")    
>>> datetime.strftime(date, "%Y-%m-%d")
'2014-01-04'

Python datetime strftime() Python datetime strftime()

How strptime and strftime work strptime和strftime如何工作

from datetime import datetime
date = datetime.strptime("1/4/2014", "%m/%d/%Y")
print(datetime.strftime(date, "%Y-%m-%d"))
'2014-01-04'

Abdou's suggestion using the datetime module is best, because you get the benefit of datetime's sanity-checking of the values. Abdou建议使用datetime模块是最好的,因为您可以获得datetime对值的完整性检查的好处。 If you want to do it using only string manipulations, then notice that you can supply a fill character when invoking a string's rjust method: 如果您只想使用字符串操作,那么请注意,在调用字符串的rjust方法时,您可以提供填充字符:

>>> "1".rjust(2,"0")
'01'

so: 所以:

>>> x = "1/4/2345"
>>> f = x.split("/")
>>> f[2] + "-" + f[0].rjust(2,"0") + "-" + f[1].rjust(2,"0")
'2345-01-04'

Assuming that you don't need to validate the input dates, you don't need any if statements, or date processing functions: you can do it all with the string .split and .format methods. 假设您不需要验证输入日期,则不需要任何if语句或日期处理函数:您可以使用字符串.split.format方法完成所有操作。

def us_date_to_iso(us_date):
    return '{2}-{0:>02}-{1:>02}'.format(*us_date.split('/'))

# test

for s in ('1/4/2014', '1/11/1999', '31/5/2015', '25/12/2016'):
    print(s, us_date_to_iso(s))

output 产量

1/4/2014 2014-01-04
1/11/1999 1999-01-11
31/5/2015 2015-31-05
25/12/2016 2016-25-12

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

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