Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to shift a datetime object by 12 hours in python

Datetime objects hurt my head for some reason. I am writing to figure out how to shift a date time object by 12 hours. I also need to know how to figure out if two date time object's differ by say 1 minute or more.

like image 459
Richard Avatar asked Sep 07 '10 15:09

Richard


People also ask

How do you add 2 hours in Python?

Use the timedelta() class from the datetime module to add hours to datetime, e.g. result = dt + timedelta(hours=10) . The timedelta class can be passed a hours argument and adds the specified number of hours to the datetime.


2 Answers

The datetime library has a timedelta object specifically for this kind of thing:

import datetime

mydatetime = datetime.now() # or whatever value you want
twelvelater = mydatetime + datetime.timedelta(hours=12)
twelveearlier = mydatetime - datetime.timedelta(hours=12)

difference = abs(some_datetime_A - some_datetime_B)
# difference is now a timedelta object

# there are a couple of ways to do this comparision:
if difference > timedelta(minutes=1):
    print "Timestamps were more than a minute apart"

# or: 
if difference.total_seconds() > 60:
    print "Timestamps were more than a minute apart"
like image 147
Amber Avatar answered Sep 28 '22 08:09

Amber


You'd use datetime.timedelta for something like this.

from datetime import timedelta

datetime arithmetic works kind of like normal arithmetic: you can add a timedelta object to a datetime object to shift its time:

dt = # some datetime object
dt_plus_12 = dt + timedelta(hours=12)

Also you can subtract two datetime objects to get a timedelta representing the difference between them:

dt2 = # some other datetime object
ONE_MINUTE = timedelta(minutes=1)
if abs(dt2 - dt) > ONE_MINUTE:
    # do something
like image 42
David Z Avatar answered Sep 28 '22 09:09

David Z