Let pandas to parse dates, but then some days with months should be swapped:

df['accepted_date'] = pd.to_datetime(df['accepted_date'])

So better is use to_datetime with format and parameter errors='coerce', what return only matched datetimes with NaT for non matched. Last use combine_first for join all Series - NaT are replaced by values from another Series:

df = pd.DataFrame({'accepted_date':['2017-01-02','07-08-2017','20-03-2017','2017-01-04']})

d1 = pd.to_datetime(df['accepted_date'], format='%d-%m-%Y', errors='coerce')
d2 = pd.to_datetime(df['accepted_date'], format='%Y-%m-%d', errors='coerce')

df['accepted_date1'] = d1.combine_first(d2)
df['accepted_date2'] = pd.to_datetime(df['accepted_date'])
print (df)
  accepted_date accepted_date1 accepted_date2
0    2017-01-02     2017-01-02     2017-01-02
1    07-08-2017     2017-08-07     2017-07-08 <-swapped dd-mm
2    20-03-2017     2017-03-20     2017-03-20
3    2017-01-04     2017-01-04     2017-01-04

Detail:

print (d1)
0          NaT
1   2017-08-07
2   2017-03-20
3          NaT
Name: accepted_date, dtype: datetime64[ns]

print (d2)
0   2017-01-02
1          NaT
2          NaT
3   2017-01-04
Name: accepted_date, dtype: datetime64[ns]

EDIT:

Another solution is use parameter dayfirst=True:

df['accepted_date3'] = pd.to_datetime(df['accepted_date'], dayfirst=True)
print (df)
  accepted_date accepted_date3
0    2017-01-02     2017-01-02
1    07-08-2017     2017-08-07
2    20-03-2017     2017-03-20
3    2017-01-04     2017-01-04
Answer from jezrael on Stack Overflow
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.to_datetime.html
pandas.to_datetime — pandas 3.0.1 documentation - PyData |
Convert argument to datetime · This function converts a scalar, array-like, Series or DataFrame/dict-like to a pandas datetime object
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › change-string-to-date-in-pandas-dataframe
Change String To Date In Pandas Dataframe - GeeksforGeeks
July 23, 2025 - Explanation:The code converts date strings to datetime using pd.to_datetime() and formats them as DD-MM-YYYY using .dt.strftime(), storing the result in 'Formatted_Date'. astype() method allows direct conversion of a column’s data type.
Discussions

python - Pandas, convert datetime format mm/dd/yyyy to dd/mm/yyyy - Stack Overflow
Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal. ... Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... The default format of csv is dd/mm/yyyy... More on stackoverflow.com
🌐 stackoverflow.com
python - Convert date string YYYY-MM-DD to YYYYMM in pandas - Stack Overflow
Is there a way in pandas to convert my column date which has the following format '1997-01-31' to '199701', without including any information about the day? I tried solution of the following form:... More on stackoverflow.com
🌐 stackoverflow.com
python - Convert pandas datetime column yyyy-mm-dd to YYYYMMDD - Stack Overflow
I have a dataframe with datetime column in the format yyyy-mm-dd. I would like to have it in integer format yyyymmdd. When I try: x=dates.apply(dt.datetime.strftime('%Y%m%d')).astype(int) ... This doesn't work if I try to pass an array. I know that if I pass just on element it will convert, but what is a more pythonic way to do it? I did try using lambda but that didn't work either. ... have you tried: df.dates.apply(lambda x: x.replace("-", "")) because it seems like the data is in string ... More on stackoverflow.com
🌐 stackoverflow.com
pandas - Convert integer (YYYYMMDD) to date format (mm/dd/yyyy) in python - Stack Overflow
I have following dataframe. id int_date 1 20160228 2 20161231 3 20160618 4 20170123 5 20151124 How to convert above date in int format to date format of mm/dd/yyyy? Want this in More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 3
16

You can use the parse_dates and dayfirst arguments of pd.read_csv, see: the docs for read_csv()

df = pd.read_csv('myfile.csv', parse_dates=['Date'], dayfirst=True)

This will read the Date column as datetime values, correctly taking the first part of the date input as the day. Note that in general you will want your dates to be stored as datetime objects.

Then, if you need to output the dates as a string you can call dt.strftime():

df['Date'].dt.strftime('%d/%m/%Y')
2 of 3
1

When I use again this: df['Date'] = pd.to_datetime(df['Date']), it gets back to the previous format.

No, you cannot simultaneously have the string format of your choice and keep your series of type datetime. As remarked here:

datetime series are stored internally as integers. Any human-readable date representation is just that, a representation, not the underlying integer. To access your custom formatting, you can use methods available in Pandas. You can even store such a text representation in a pd.Series variable:

formatted_dates = df['datetime'].dt.strftime('%m/%d/%Y')

The dtype of formatted_dates will be object, which indicates that the elements of your series point to arbitrary Python times. In this case, those arbitrary types happen to be all strings.

Lastly, I strongly recommend you do not convert a datetime series to strings until the very last step in your workflow. This is because as soon as you do so, you will no longer be able to use efficient, vectorised operations on such a series.

🌐
Educative
educative.io › answers › what-is-the-pandastodatetime-method
What is the pandas.to_datetime() method?
arg: an integer, float, string, list, or dict object to convert into a DateTime object. dayfirst: set it to true if the input contains the day first. yearfirst: set it to true if the input contains the year first. utc: returns the UTC DatetimeIndex if True. format: specifies the position of the day, month, and year in the date. import pandas as pd · # input in mm.dd.yyyy format ·
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas change string to date in dataframe
Pandas Change String to Date in DataFrame - Spark By {Examples}
June 26, 2025 - Now, convert the datatype into datetime(‘yyyy-mm-dd’) format by using df["InsertedDate"] = pd.to_datetime(df["InsertedDate"],format='%y%m%d') function. # Use pandas.to_datetime() to convert string to "yyyymmdd" format df["InsertedDate"] ...
🌐
Saturn Cloud
saturncloud.io › blog › how-to-convert-strings-in-a-pandas-data-frame-to-a-date-data-type
How to Convert Strings in a Pandas Dataframe to a Date Data Type | Saturn Cloud Blog
January 25, 2024 - Here’s an example of how to use the to_datetime() function to convert a column of strings to date data types: import pandas as pd # create a sample data frame df = pd.DataFrame({'date': ['2022-01-01', '2022-01-02', '2022-01-03']}) # convert ...
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › converting-string-yyyy-mm-dd-into-datetime-in-python
Converting string into DateTime in Python - GeeksforGeeks
May 1, 2025 - For large datasets, especially in CSV or Excel format, pandas.to_datetime() efficiently converts multiple date strings into DateTime objects, handling various formats, missing values, and errors.
🌐
Statology
statology.org › home › pandas: how to convert date to yyyymmdd format
Pandas: How to Convert Date to YYYYMMDD Format
November 16, 2022 - #convert date column to datetime df['date_column'] = pd.to_datetime(df['date_column']) #convert date to YYYYMMDD format df['date_column'] = df['date_column'].dt.strftime('%Y%m%d').astype(int) The following example shows how to use this syntax in practice. Suppose we have the following pandas DataFrame that shows the sales made by some company on various dates:
🌐
Data to Fish
datatofish.com › string-to-datetime-pandas
How to Convert Strings to Datetime in a pandas DataFrame
import pandas as pd data = {'date': ['01/15/2021', '02/15/2021', '03/15/2021']} df = pd.DataFrame(data) print(df) print(df.dtypes) date 0 01/15/2021 1 02/15/2021 2 03/15/2021 date object dtype: object · The date column is of type object/string. Notice that the dates are formatted as mm/dd/yyyy.
Top answer
1 of 2
25

If your column is a string, you will need to first use `pd.to_datetime',

df['Date'] = pd.to_datetime(df['Date'])

Then, use .dt datetime accessor with strftime:

df = pd.DataFrame({'Date':pd.date_range('2017-01-01', periods = 60, freq='D')})

df.Date.dt.strftime('%Y%m%d').astype(int)

Or use lambda function:

df.Date.apply(lambda x: x.strftime('%Y%m%d')).astype(int)

Output:

0     20170101
1     20170102
2     20170103
3     20170104
4     20170105
5     20170106
6     20170107
7     20170108
8     20170109
9     20170110
10    20170111
11    20170112
12    20170113
13    20170114
14    20170115
15    20170116
16    20170117
17    20170118
18    20170119
19    20170120
20    20170121
21    20170122
22    20170123
23    20170124
24    20170125
25    20170126
26    20170127
27    20170128
28    20170129
29    20170130
30    20170131
31    20170201
32    20170202
33    20170203
34    20170204
35    20170205
36    20170206
37    20170207
38    20170208
39    20170209
40    20170210
41    20170211
42    20170212
43    20170213
44    20170214
45    20170215
46    20170216
47    20170217
48    20170218
49    20170219
50    20170220
51    20170221
52    20170222
53    20170223
54    20170224
55    20170225
56    20170226
57    20170227
58    20170228
59    20170301
Name: Date, dtype: int32
2 of 2
0

The error in the OP occurred because datetime.datetime.strftime was called without a datetime/date argument in apply(). The format= should be passed as a separate argument to apply(), which will be passed off to strftime() as the format.

from datetime import datetime
x = dates.apply(datetime.strftime, format='%Y%m%d').astype(int)

If the date were strings (instead of datetime/date), then str.replace() should do the job.

x = dates.str.replace('-', '').astype(int)

# using apply
x = dates.apply(lambda x: x.replace('-', '')).astype(int)

A mildly interesting(?) thing to note is that both .dt.strftime and str.replace of pandas are not optimized, so calling Python's strftime and str.replace via apply() is actually faster than the pandas counterparts (in the case of strftime, it is much faster).

dates = pd.Series(pd.date_range('2020','2200', freq='d'))

%timeit dates.dt.strftime('%Y%m%d')
# 719 ms ± 41.5 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit dates.apply(datetime.strftime, format='%Y%m%d')
# 472 ms ± 34.5 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

dates = dates.astype(str)

%timeit dates.str.replace('-', '')
# 30.9 ms ± 2.46 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit dates.apply(lambda x: x.replace('-', ''))
# 26 ms ± 183 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas convert date (datetime) to string format
Pandas Convert Date (datetime) to String Format - Spark By {Examples}
June 30, 2025 - Details of the string format can be found in the Python string format doc. Note: strftime stands for String From Time. # Change in datetime format to other format df['ConvertedDate'] = df['DateTypeCol'].dt.strftime('%m/%d/%Y') print("After converting datatime to string format:\n", df) Yields below output. This example changes the DateTypeCol (datetime) into MM/DD/YYYY format and stores into ConvertedDate column.
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › convert-the-column-type-from-string-to-datetime-format-in-pandas-dataframe
Convert Column Type from String to Datetime Format in Pandas Dataframe - GeeksforGeeks
The format='%y%m%d' tells Pandas the input uses two-digit years. The “Date” column is converted to datetime64[ns]. When the column is already in yyyymmdd format, use pd.to_datetime() with the %Y%m%d format to convert it directly to ...
Published   November 1, 2025
Top answer
1 of 2
93

to_datetime accepts a format string:

In [92]:

t = 20070530
pd.to_datetime(str(t), format='%Y%m%d')
Out[92]:
Timestamp('2007-05-30 00:00:00')

example:

In [94]:

t = 20070530
df = pd.DataFrame({'date':[t]*10})
df
Out[94]:
       date
0  20070530
1  20070530
2  20070530
3  20070530
4  20070530
5  20070530
6  20070530
7  20070530
8  20070530
9  20070530
In [98]:

df['DateTime'] = df['date'].apply(lambda x: pd.to_datetime(str(x), format='%Y%m%d'))
df
Out[98]:
       date   DateTime
0  20070530 2007-05-30
1  20070530 2007-05-30
2  20070530 2007-05-30
3  20070530 2007-05-30
4  20070530 2007-05-30
5  20070530 2007-05-30
6  20070530 2007-05-30
7  20070530 2007-05-30
8  20070530 2007-05-30
9  20070530 2007-05-30
In [99]:

df.dtypes
Out[99]:
date                 int64
DateTime    datetime64[ns]
dtype: object

EDIT

Actually it's quicker to convert the type to string and then convert the entire series to a datetime rather than calling apply on every value:

In [102]:

df['DateTime'] = pd.to_datetime(df['date'].astype(str), format='%Y%m%d')
df
Out[102]:
       date   DateTime
0  20070530 2007-05-30
1  20070530 2007-05-30
2  20070530 2007-05-30
3  20070530 2007-05-30
4  20070530 2007-05-30
5  20070530 2007-05-30
6  20070530 2007-05-30
7  20070530 2007-05-30
8  20070530 2007-05-30
9  20070530 2007-05-30

timings

In [104]:

%timeit df['date'].apply(lambda x: pd.to_datetime(str(x), format='%Y%m%d'))

100 loops, best of 3: 2.55 ms per loop
In [105]:

%timeit pd.to_datetime(df['date'].astype(str), format='%Y%m%d')
1000 loops, best of 3: 396 µs per loop
2 of 2
2

You don't need to cast to strings, pd.to_datetime() can parse

int, float, str, datetime, list, tuple, 1-d array, Series, DataFrame/dict-like

so directly calling it with the specific format= should work.

df['date'] = pd.to_datetime(df['date'], format='%Y%m%d')

One useful parameter is errors=. By setting it to 'coerce', you can get NaT values for "broken" dates instead of having an error raised.

df['date'] = pd.to_datetime(df['date'], format='%Y%m%d', errors='coerce')
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-string-to-datetime-strptime
How To Convert a String to a datetime Object in Python | DigitalOcean
December 13, 2024 - To convert a date string in the mm dd yyyy format to a datetime object in Python, you can use the datetime.strptime method from the datetime module:
🌐
Saturn Cloud
saturncloud.io › blog › converting-a-column-to-date-format-in-pandas-dataframe
Converting a Column to Date Format in Pandas Dataframe | Saturn Cloud Blog
October 27, 2023 - The easiest and most straightforward way to convert a column to date format is to use the to_datetime() function provided by Pandas.
🌐
Jingwen Zheng
jingwen-z.github.io › converting-between-datetime-and-string
Python: Converting between datetime and string - Jingwen Zheng
January 15, 2019 - DD/MM/YYYY · DD/MM/YY · ... '2019-01-09' >>> dt_stamp.strftime('%F') '2019-01-09' %Y means four-digit year, %m presents two-digit month, %d describes two-digit day, %F is the shortcut for %Y-%m-%d....
🌐
Reddit
reddit.com › r/learnpython › how can i convert yyyy-mm-dd to m/d/yyyy
r/learnpython on Reddit: How can I convert YYYY-MM-DD to M/D/YYYY
July 12, 2021 -

Hello all,

I have an excel file with about 100 columns, and 30 or so are dates, I would like to convert all the date formats

from:

 YYYY-MM-DD 

to

  M/D/YYYY

I was able to change it to MM/DD/YYYY using the following code

def fmt(input_dt):
if isnull(input_dt):
    return ""
else:
    return input_dt.strftime("%m/%d/%Y")

for col in df.columns:
if df[col].dtype == 'datetime64[ns]':
    df[col] = df[col].apply(fmt)

but that gives me

MM/DD/YYYY

I also need it to be datetime when exported back to excel.

I looked into the documentation

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes

But it does not have M/D/YYYY any suggestions would be helpful. Thank you! Also if there is a more pythonic way to write it please let me know