[英]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.我有一个 MySQL 数据库,并且有一列存储了日期。 Now the requirement is I need to replace the dd with YY.现在的要求是我需要用 YY 替换 dd。 and I want to do this using python(Pandas)我想使用 python(Pandas) 来做到这一点
for eg date that i have is 2032-11-16, and I want 2016-11-32.例如,我的日期是 2032-11-16,我想要 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.还请告诉我如何在 mysql 中保存更新。
datetime
module could help you with that: datetime
模块可以帮助您:
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"
.打印"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"
.这将打印"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:好吧,如果您知道日期字符串的格式为 YYDD-MM-YY,那么只需使用以下命令:
new_str = old_str;
new_str[2:4] = old_str[8:10]
new_str[8:10] = old_str[2:4]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.