简体   繁体   中英

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. However I am only given 1/4/2014 (without zeroes). Is there a clean and more efficient way of converting this in python 3 rather than writing a bunch of if statements?

>>> 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()

How strptime and strftime work

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. 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:

>>> "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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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