简体   繁体   中英

How to change the date from YYYY-MM-DD to YYDD-MM-YY in python

I have a MySQL database, and there is a column in which I have stored the date. Now the requirement is I need to replace the dd with YY. and I want to do this using python(Pandas)

for eg date that i have is 2032-11-16, and I want 2016-11-32.

uptill now my approach is shown below

df = pd.read_csv('p1006_freight_rates.csv')
df['year'] = zip(*df['date'].apply(lambda x: (x[:4], x[5:])))

the above approach is absolutely wrong, I have also tried the string replace but that too had some issue.

and also please tell me how to save the update in mysql.

datetime module could help you with that:

datetime.datetime.strptime(date_string, format1).strftime(format2)

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

prints "01/25/13" .

If you can't live with the leading zero, try this:

dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)

This prints "1/25/13" .

EDIT: This may not work on every platform:

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%-m/%d/%y')

A simple and straight forward method would be like this:

xx = [
    '2032-11-16',
    '2011-22-33'
]
df = pd.DataFrame(xx,columns=['date'])
df['new_date'] = df.date.map(lambda x:x[:2]+x[-2:]+x[4:8]+x[2:4])
df

Well, if you have a date string that you KNOW is in the format YYDD-MM-YY, then just use this:

new_str = old_str;
new_str[2:4] = old_str[8:10]
new_str[8:10] = old_str[2:4]

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