How would I be able to write a code that will enable the starting and the ending year in dates
. I want to use either pandas or numpy to show the starting and the ending year.
import numpy as np
import pandas as pd
dates = ['2017-09-01 00:00:00', '2017-10-01 00:00:00', '2017-11-01 00:00:00', '2017-11-01 00:00:00', '2017-11-01 00:00:00', '2017-12-01 00:00:00', '2018-01-01 00:00:00', '2018-02-01 00:00:00', '2018-03-01 00:00:00', '2018-04-01 00:00:00', '2018-05-01 00:00:00', '2018-06-01 00:00:00', '2018-07-01 00:00:00', '2018-08-01 00:00:00', '2018-09-01 00:00:00', '2018-10-01 00:00:00', '2018-11-01 00:00:00', '2018-12-01 00:00:00', '2018-12-01 00:00:00', '2019-01-01 00:00:00']
Expected Output:
Starting year: 2017
Ending year: 2019
CodePudding user response:
In your case let us do
pd.Series(pd.to_datetime(dates)).dt.year.agg(StartYear = 'min', EndYear = 'max')
Out[245]:
StartYear 2017
EndYear 2019
dtype: int64
CodePudding user response:
Another solution:
mn, mx = (m := pd.to_datetime(dates)).min(), m.max()
print(f"Starting year: {mn.year}\nEnding year: {mx.year}")
Prints:
Starting year: 2017
Ending year: 2019