I have a dataframe that contains a series of dates, eg:
0 2014-06-17
1 2014-05-05
2 2014-01-07
3 2014-06-29
4 2014-03-15
5 2014-06-06
7 2014-01-29
Now, I need a way to convert these dates to the sequential day of the year, eg
0 168
1 125
2 7
3 180
4 74
5 157
7 29
All the values are within the same year. The opposite problem has been asked many times - converting the sequential day of the year to a date, but I need to do the opposite. Is there an easy way to do this with Pandas? Thanks!
EDIT: Answered by piRSquared. Thank you!
Option 1
time-date-components
Link from @root
Use dt.dayofyear
df.iloc[:, 0].dt.dayofyear
0 168
1 125
2 7
3 180
4 74
5 157
7 29
Name: 1, dtype: int64
Option 2
strftime.org
Use dt.strftime('%-j')
df.iloc[:, 0].dt.strftime('%-j')
0 168
1 125
2 7
3 180
4 74
5 157
7 29
Name: 1, dtype: object
Yes, I did it. Please refer my below code.
Step 1: Make array of String datatype and add dates in string format.
Step 2: Use for loop because you have multiple dates.
Step 3: Convert String to Date format.
Step 4: Conver Date to LocalDate format.
Step 5: Use getDatOfYear() inbuilt function to get sequential day of the year.
package test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
public class ShubhamDateClass{
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String[] dateForTest = {"17-JUN-2014","05-MAY-2014","07-JAN-2017","20-JUN-2014","15-MAR-2014", "6-JUN-2014", "29-JAN-2014"};
for(int i=0;i<dateForTest.length;i++){
try {
Date date = formatter.parse(dateForTest[i]);
System.out.print(formatter.format(date)+" --- ");
LocalDate dateTest = Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
int dayOfYear2 = dateTest.getDayOfYear();
System.out.println(dayOfYear2);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.