I am receiving a datetime string which I am converting into python datetime. My objective was to add 1 second to this datetime.
def modify_date_by_1_second(date):
if date!="":
try:
date_time_obj = datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%fZ')
date_time_obj = date_time_obj timedelta(seconds=1)
return date_time_obj.isoformat()[:-3] 'Z'
except Exception as e:
return None
else:
return None
The above function gives result:
Passed Case:
Input = "2017-09-15T18:30:15.000Z"
Output = "2017-09-15T18:30:16.000Z"
Failed Case:
Input = "2017-09-15T18:30:00.000Z"
Output = "2017-09-15T18:30Z"
I checked by printing the date_time_obj
object, it outputs datetime.datetime(2017, 12, 29, 18, 30)
Here seconds are not mentioned.
Is there any way to achieve this for this specific kind of input?
CodePudding user response:
It is YOU that is stripping the seconds off, with your [:-3]
.
Per the documentation, the .isoformat
method does not include the microseconds if the value is 0. Perhaps you need to check the length of the string before you whack off your characters.
Just to elaborate, if the datetime value includes any microseconds at all, the return is
2017-09-15T18:30:15.000001
Which you truncate to:
2017-09-15T18:30:15.000Z
But if the microseconds value is zero, isoformst
returns this:
2017-09-15T18:30:15
which you truncate to
2017-09-15T18:30Z