
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
Example
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)
Output
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.
- Related Articles
- 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?
- Python Pandas - Get the UTC Offset Time
- 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?
- How can I make a time delay in Python?
- How can I get the current contents of an element in webdriver?
- How to apply Affine Transformation on an image in OpenCV Python?
- How can I list all cookies on the current page with JavaScript?
- How to return the current CPU time in Python?
- How can I plot two different spaced time series on one same plot in Python Matplotlib?
- How do I get the current date and time in JavaScript?
- Getting current time in Python
- How to apply Perspective Transformations on an image using OpenCV Python?
