How would I go about changing only the year in a datetime object?
I need to call a number of dates from excel, and if the dates I call are before todays date, set the year to 2099.
e.g. date that is called: 15/11/2010 needs to be set to 15/11/2099
Is this doable? or would it be best to change the whole date?
DateTime is immutable type. You cannot change year or any other part of it. You should create new DateTime instance with new year.
In pandas, a string is converted to a datetime object using the pd. to_datetime() method. pd. DateOffset() method is used to add years to the created pandas object.
Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.
You just need to create a new DateTime
since DateTime
is an immutable struct:
DateTime newDt = new DateTime(2099, dt.Month, dt.Day);
If you want to handle the leapyear issue(source date is in leapyear but target year not), you could use following extension method:
public static DateTime ChangeYear(this DateTime dt, int newYear)
{
return dt.AddYears(newYear - dt.Year);
}
This will retain even the Ticks
and the Kind
, so it's better than using the DateTime
constructor. It will return 02/28/2099
if the orginal DateTime was 02/29/2016
(leap year).
You can use it for example in this way:
DateTime dt = new DateTime(2016, 2, 29);
DateTime newDt = dt.ChangeYear(2099);
DateTime
is immutable type. You cannot change year or any other part of it. You should create new DateTime
instance with new year. There is no other option.
var date1 = DateTime.Now;
var date2 = new DateTime(2099, date1.Month, date1.Day);
Though you can write an extension if you need to do it often:
public static DateTime JumpToYear(this DateTime date, int year)
{
// you can also provide Hour, Minute, Second and Millisecond
return new DateTime(year, date.Month, date.Day);
}
Usage:
var date2 = date1.JumpToYear(2099);
Note: February 29 date can become invalid when you change 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