how to change dd-mm-yyyy date format to yyyy-dd-mm in pandas
how to change dd-mm-yyyy date format to yyyy-dd-mm in pandas
How to change dd-mm-yyyy date format to yyyy-dd-mm in pandas. I have a datefield which is already in dd-mm-yyyy format but when I try
df[('date')] = pd.to_datetime(df[('date')]).dt.strftime('%Y-%m-%d')
it gives output a yyyy-dd-mm
3 Answers
3
I believe this is what you needed.
import pandas as pd
df = pd.read_csv("dates.csv")
df
id date
0 1 25/06/2018
1 2 14-11-2005
2 3 03/10/2010
3 4 13-08-2008
4 5 05-05-2005
Here no need to specify the format as you have tried.
df['date'] =pd.to_datetime(df['date'])
df
id date
0 1 2018-06-25
1 2 2005-11-14
2 3 2010-03-10
3 4 2008-08-13
4 5 2005-05-05
Can you please specify in which format you wanted it to be? Ex:-
yyyy-mm-dd
(or) yyyy/mm/dd
(or) dd-mm-yyyy
(or) dd/mm/yyyy
– msr_003
Aug 30 at 6:20
yyyy-mm-dd
yyyy/mm/dd
dd-mm-yyyy
dd/mm/yyyy
My date format is dd/mm/yyyy but i want it in yyyy-mm-dd format.. But when i do pd.datetime it gives me result as yyyy-dd-mm
– Rahul
Aug 30 at 6:32
I've tested with
dd/mm/yyyy
format and the same function is giving me in yyyy-mm-dd
format, not in yyyy-dd-mm
format.– msr_003
Aug 30 at 6:37
dd/mm/yyyy
yyyy-mm-dd
yyyy-dd-mm
Pandas datetime
series data do not have an inherent string format.
datetime
datetime
values are stored internally as integers. For more details, see this answer. String representations are just that, representations. For example, when you use the print
command, a specific string representation is used so that data is displayed in a human-readable way.
datetime
print
For most purposes, you should not worry about the representation. If you need a format different to the default representation, i.e. "YYYY-MM-DD", you can use pd.Series.dt.strftime
and specify a string format. For this Python's strftime
directives is a useful resource.
pd.Series.dt.strftime
strftime
Use this:
import pandas as pd
df['date'] = pd.to_datetime(df['date'],format='%d-%m-%Y').dt.strftime('%Y-%m-%d')#specify input format '%d-%m-%Y' and output format '%Y-%m-%d' or change output as desired i.e. %d/%m/%Y to give dd/mm/yyyy
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Hi,even if I don't specify it gives me result in yyyy-mm-dd... Does it matter if the earlier date format is dd/mm/yyyy delimiter is (/) rather than (-) ??
– Rahul
Aug 30 at 6:03