Pandas DateTime Formating - python

I'm trying to figure out how to reformat a date in a pandas df. The source date is a string in the format of %Y-%m-%d %H:%M:%S. I use the following code to convert it do a date field in a format=%Y-%m-%d.
df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d').dt.date
How do I convert a date field in the format of %Y-%m-%d into %m/%d/%Y ?
Thanks!

i think this should help
df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d').dt.date
df['Date'] = df['Date'].dt.strftime('%m/%d/%Y')
you can try a one liner
df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d').dt.strftime('%m/%d/%Y')

Related

Pandas converting date time in string to datetime format

I have a column in Pandas dataframe which is a datetime entry column in string.
I have tried using the the syntax but it gives rise to this error.
Syntax
pd.to_datetime(df['Datetime'], format = '%y-%m-%d %H:%M:%S')
Error
time data '2020-11-01 16:23:12' does not match format '%y-%m-%d %H:%M:%S'
Try %Y,
this is the cheatsheet: https://strftime.org/
Yes, you've used the wrong format for the year.
pd.to_datetime(df["Datetime"], format="%Y-%m-%d %H:%M:%S")

Convert Month Year to YYYY-MM-DD date format Python Pandas

i want to convert Month and year to YYYY-MM-DD in a dataframe in panda, the date will be the first day of that month
i try using this
pd.to_datetime(df, format='%Y-%m-%d', errors='ignore')
I expected the result to be
Try with format '%b,%Y':
df['date']=pd.to_datetime(df['date'], format='%b,%Y', errors='coerce')
OR
Don't use format at all and let pandas infer it:
df['date']=pd.to_datetime(df['date'], errors='coerce')
For more info regarding format code see docs

Converting dates to datetime64 results in day and month places getting swapped

I am pulling a time series from a csv file which has dates in "mm/dd/yyyy" format
df = pd.read_csv(lib_file.csv)
df['Date'] = df['Date'].apply(lambda x:datetime.strptime(x,'%m/%d/%Y').strftime('%d/%m/%Y'))
below is the output
I convert dtypes for ['Date'] from object to datetime64
df['Date'] = pd.to_datetime(df['Date'])
but that changes my dates as well
how do I fix it?
Try this:
df['Date'] = pd.to_datetime(df['Date'], infer_datetime_format=True)
This will infer your dates based on the first non-NaN element which is being correctly parsed in your case and will not infer the format for each and every row of the dataframe.
just using the below code helped
df = pd.read_csv(lib_file.csv)
df['Date'] = pd.to_datetime(df['Date])

Convert Raw Date into Year / Month / Day of Week in Pandas

I have a Pandas dataframe with raw dates formatted as such "19990130". I want to convert these into new columns: 'year', 'month', and 'dayofweek'.
I tried using the following:
pd.to_datetime(df['date'], format='%Y%m%d', errors='ignore').values
Which does give me an array of datetime objects. However, the next step I tried was using .to_pydatetime() and then .year to try to get the year out, like this:
pd.to_datetime(df['date'], format='%Y%m%d', errors='ignore').values.to_pydatetime().year
This works when I test a single value, but with a Pandas dataframe. I get:
'numpy.ndarray' object has no attribute 'to_pydatetime'
What's the easiest way to extract the year, month, and day of week from this data?
Try:
s = pd.to_datetime(df['date'], format='%Y%m%d', errors='coerce')
s.dt.year
# or
# s.dt.month, etc

Convert date string YYYY-MM-DD to YYYYMM in pandas

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:
df['DATE'] = df['DATE'].apply(lambda x: datetime.strptime(x, '%Y%m'))
but I obtain this error : 'ValueError: time data '1997-01-31' does not match format '%Y%m''
Probably the reason is that I am not including the day in the format. Is there a way better to pass from YYYY-MM_DD format to YYYYMM in pandas?
One way is to convert the date to date time and then use strftime. Just a note that you do lose the datetime functionality of the date
df = pd.DataFrame({'date':['1997-01-31' ]})
df['date'] = pd.to_datetime(df['date'])
df['date'] = df['date'].dt.strftime('%Y%m')
date
0 199701
Might not need to go through the datetime conversion if the data are sufficiently clean (no incorrect strings like 'foo' or '001231'):
df = pd.DataFrame({'date':['1997-01-31', '1997-03-31', '1997-12-18']})
df['date'] = [''.join(x.split('-')[0:2]) for x in df.date]
# date
#0 199701
#1 199703
#2 199712
Or if you have null values:
df['date'] = df.date.str.replace('-', '').str[0:6]

Categories