i have a model which holds data for a game, how would i add 2 hours and 1 day onto the 'starts' field?
class Game(models.Model):
starts = models.DateTimeField(auto_now_add=True)
ends = models.DateTimeField()
does anyone have a solution for this?
Use the timedelta() class from the datetime module to add hours to datetime, e.g. result = dt + timedelta(hours=10) . The timedelta class can be passed a hours argument and adds the specified number of hours to the datetime.
Step 1: If the given timestamp is in a string format, then we need to convert it to the datetime object. Step 2: Create an object of timedelta, to represent an interval of N hours. Step 3: Subtract the timedelta object from the datetime object.
from datetime import timedelta
obj.starts += timedelta(days=1, hours=2)
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