Python Timedelta Example
Below code show how to use timedelta in Python to add and subtract day and time.
---------------------------------------------------
#Output
365 days, 5:01:00
Today's date: 2019-04-20 12:06:05.323435
One year from now will be: 2020-04-19 12:06:05.323435
In 2 days it will be: 2019-04-22 12:06:05.323435
In 3 weeks it will be: 2019-05-11 12:06:05.323435
1 week ago it was: 2019-04-13 12:06:05.323435
Days till Christmas: 219 days, 0:00:00
# # Python timedelta # from datetime import date from datetime import datetime from datetime import timedelta # construct a basic timedelta and print it print(timedelta(days=365, hours=5, minutes=1)) # print today's date now = datetime.now() print("Today's date: ", str(now)) print("One year from now will be: ", str(now + timedelta(days=365))) print("In 2 days it will be: ", str(now + timedelta(days=2))) print("In 3 weeks it will be: ", str(now + timedelta(weeks=3))) print("1 week ago it was: ", str(now - timedelta(weeks=1))) ### How many days until Christmas day Day of current year today = date.today() christmas_day = date(today.year, 12, 25) print("Days till Christmas: ", str(christmas_day - today))
---------------------------------------------------
#Output
365 days, 5:01:00
Today's date: 2019-04-20 12:06:05.323435
One year from now will be: 2020-04-19 12:06:05.323435
In 2 days it will be: 2019-04-22 12:06:05.323435
In 3 weeks it will be: 2019-05-11 12:06:05.323435
1 week ago it was: 2019-04-13 12:06:05.323435
Days till Christmas: 219 days, 0:00:00
Comments
Post a Comment