- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can I apply an offset on the current time in Python?
Whenever you want to add or subtract(apply an offset) to a date/time, use a datetime.datetime(), then add or subtract datetime.timedelta() instances. A timedelta object represents a duration, the difference between two dates or times. The timedelta constructor has the following function signature −
datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
Note − All arguments are optional and default to 0. Arguments may be ints, longs, or floats, and may be positive or negative. You can read more about it here − https://docs.python.org/2/library/datetime.html#timedelta-objects
An example of using the timedelta objects and dates −
import datetime old_time = datetime.datetime.now() print(old_time) new_time = old_time - datetime.timedelta(hours=2, minutes=10) print(new_time)
This will give the output −
2018-01-04 11:09:00.694602 2018-01-04 08:59:00.694602
timedelta() arithmetic is not supported for datetime.time() objects; if you need to use offsets from an existing datetime.time() object, just use datetime.datetime.combine() to form a datetime.datetime() instance, do your calculations, and 'extract' the time again with the .time() method.
- How can I get the current time and date in Kotlin?
- How to return the time-zone offset in minutes for the current locale?
- How can I get the current week using Python?
- How do I display the current date and time in an Android application?
- How do I display the current date and time in an iOS application?
- Python Pandas - Get the UTC Offset Time
- How can I get the current contents of an element in webdriver?
- How do I get the current time zone of MySQL?
- How can I make a time delay in Python?
- How can I add an image on EditText?
- How to return the current CPU time in Python?
- Getting current time in Python
- How can I get the current screen orientation in Android?