Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datetime and timedelta

My timezone is UTC+5.

So when i do datetime.datetime.now() it gives:

2012-07-14 06:11:47.318000
#note its 6AM

I wanted to subtract 5 hours from it so that it becomes equal to datetime.datetime.utcnow() so i did:

import time
from datetime import datetime, timedelta
dt = datetime.now() - timedelta(hours=time.timezone/60/60)
print dt
#gives 2012-07-14 11:11:47.319000

"""
Here 11 is not the PM its AM i double check it by doing
print dt.strftime('%H:%M:%S %p')
#gives 11:11:47 AM
"""

You see instead of subtracting 5 hours it adds 5 hours into datetime?? Am I doing something wrong here?

like image 601
Aamir Rind Avatar asked Jul 14 '12 01:07

Aamir Rind


People also ask

What is datetime Timedelta?

A timedelta object represents a duration, the difference between two dates or times. class datetime. timedelta (days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

What is the use of Timedelta () function?

timedelta() function. 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.

What is difference between datetime and date Python?

Python datetime Classesdatetime – Allows us to manipulate times and dates together (month, day, year, hour, second, microsecond). date – Allows us to manipulate dates independent of time (month, day, year).


2 Answers

You're creating a negative timedelta. The value of time.timezone is negative:

>>> import time
>>> time.timezone
-36000

Here, I'm in UTC + 10, so your code becomes:

>>> from datetime import timedelta
>>> print timedelta(hours=time.timezone/60/60)
-1 day, 14:00:00
like image 57
jterrace Avatar answered Oct 24 '22 16:10

jterrace


The documentation is clear:

time.timezone The offset of the local (non-DST) timezone, in seconds west of UTC (negative in most of Western Europe, positive in the US, zero in the UK).

So positive UTC values have a negative timezone.

like image 26
BrenBarn Avatar answered Oct 24 '22 17:10

BrenBarn