Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python time offset

Tags:

python

time

How can I apply an offset on the current time in python?

In other terms, be able to get the current time minus x hours and/or minus m minutes and/or minus s secondes and/or minus ms milliseconds

for instance

curent time = 18:26:00.000  offset = 01:10:00.000  =>resulting time = 17:16:00.000 
like image 212
Guillaume Paris Avatar asked Dec 26 '12 17:12

Guillaume Paris


People also ask

What is offset time in Python?

The utcoffset() function is used to return a timedelta object that represents the difference between the local time and UTC time. This function is used in used in the datetime class of module datetime. Here range of the utcoffset is “timedelta(hours=24) <= offset <= timedelta(hours=24)”.

How do I remove T and Z from timestamp in Python?

To remove timestamp, tzinfo has to be set None when calling replace() function. First, create a DateTime object with current time using datetime. now(). The DateTime object was then modified to contain the timezone information as well using the timezone.

How do you set custom time in Python?

The datetime. strptime() sets the hour and minute values to the default, 0 . Note that for a two-digit year (like 15 ) you'd use %y , not %Y , which is for a four-digit year. if you need to add an amount that is negative or more than one day then only the timedelta() solution would work.

How does Python define Timedelta?

Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations. Code #1: Python3.


1 Answers

Use a datetime.datetime(), then add or subtract datetime.timedelta() instances.

>>> import datetime >>> t = datetime.datetime.now() >>> t - datetime.timedelta(hours=1, minutes=10) datetime.datetime(2012, 12, 26, 17, 18, 52, 167840) 

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:

>>> t = datetime.time(1, 2) >>> dt = datetime.datetime.combine(datetime.date.today(), t) >>> dt datetime.datetime(2012, 12, 26, 1, 2) >>> dt -= datetime.timedelta(hours=5) >>> dt.time() datetime.time(20, 2) 
like image 167
Martijn Pieters Avatar answered Sep 23 '22 23:09

Martijn Pieters