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?
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.
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') .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With