Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas to_datetime function default year

Tags:

pandas

I am newbie about pandas, when I run below code, I got a different result:

import pandas as pd

ts = pd.to_datetime("2014-6-10 10:10:10.30",format="%Y-%m-%d %H:%M:%S.%f")
print ts
ts = pd.to_datetime("6-10 10:10:10.30",format="%m-%d %H:%M:%S.%f")
print ts

The output is:

2014-06-10 10:10:10.300000
1900-06-10 10:10:10.300000

That means the default year is 1900, how can I change it to 2014 for the second one?

like image 273
lucky1928 Avatar asked Jun 18 '14 15:06

lucky1928


People also ask

How do I keep year in pandas datetime?

Suppose we want to access only the month, day, or year from date, we generally use pandas. Method 1: Use DatetimeIndex. month attribute to find the month and use DatetimeIndex. year attribute to find the year present in the Date.

How do I change date format to MM DD YYYY in pandas?

Please notice that you can also specify the output date format other than the default one, by using the dt. strftime() method. For example, you can choose to display the output date as MM/DD/YYYY by specifying dt. strftime('%m/%d/%Y') .

What is PD To_datetime ()?

to_datetime() function. The to_datetime() function is used to convert argument to datetime. Syntax: pandas.to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, utc=None, format=None, exact=True, unit=None, infer_datetime_format=False, origin='unix', cache=True) Parameters: Name.

What is DT year in Python?

dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series. dt. year attribute return a numpy array containing year of the datetime in the underlying data of the given series object.


1 Answers

You cannot write to the year attribute of a datetime, so the easiest thing to do is use replace:

In [57]:

ts = ts.replace(year=2014)
ts
Out[57]:
Timestamp('2014-06-10 10:10:10.300000')

Another possiblity is to store the current year as a string and prepend this as required, this has an advantage that you can use the same format string for all dates:

In [68]:

this_year = str(datetime.datetime.now().year)
datestr = this_year +'-' + '6-10 10:10:10.30'
pd.to_datetime(datestr,format="%Y-%m-%d %H:%M:%S.%f")
Out[68]:
Timestamp('2014-06-10 10:10:10.300000')

Can't think of a better way but you could wrap the above in a function to test if you need to set the year

like image 138
EdChum Avatar answered Dec 31 '22 19:12

EdChum