how to shift a datetime object by 12 hours in python - 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.

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"

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

Related

substracting datetime object on date level

All answers require hour, min, s, etc...
like this:
from datetime import datetime
datetime.today() - datetime.timedelta(days=1)
I don't want to create datetime object that contain all hours, minutes, seconds, etc...
Is there a way to add and substract date on higher level(date?)
What I desire:
dt = "20210601"
st_date = dt - 30days
print(st_date)
>>> "2021-05-02"
What I tried:
datetime.strptime("20210601", "%Y%m%d") - datetime.timedelta(days=30)
Outputs AttributeError: type object 'datetime.datetime' has no attribute 'timedelta' which I assume it wants all hours, mins, seconds, etc...
Try using the timedelta function instead of the datetime.timedelta function:
from datetime import datetime, timedelta
stdate = datetime.strptime("20210601", "%Y%m%d") - timedelta(days=30)
print(stdate)
Output:
2021-05-02 00:00:00

Is there a function in python that could generate date 4 weeks from current date/given date?

Is there any function in python that can generate date for example 4 weeks from now or given date?
I've gone through documentation from datetime modeule but couldnt find any example that can support my question.
four_weeks = datetime.timedelta(days=4*7)
dt = datetime.datetime.now()
print(dt + four_weeks)
Here you go:
from datetime import timedelta
from datetime import datetime
today = datetime.today()
print(today + timedelta(weeks=1))
I think the thing you're looking for is timedelta.
from datetime import timedelta
def add_weeks(dt, n_weeks):
n_days = 7 * n_weeks
return dt + timedelta(days=n_days)
In python datetime module has a class called datetime which represents a date + time, an point on time line. There is another class called timedelta that represents difference between two dates (datetiems).
You can add a date with a timedelta.
example code:
from datetime import datetime, timedelta
now = datetime.now()
duration = timedelta(days=28)
target = now + duration
print(target)

How to combine dates and times?

I want to add a time to a datetime. My initial datetime is: initial_datetime='2015-11-03 08:05:22' and is a string and this_hour and this_min are strings too. I use:
time='-7:00'
time = time.split(':')
this_hour = time[0]
this_min = time[1]
initial_datetime='2015-11-03 08:05:22'
new_date = datetime.combine(initial_datetime, time(this_hour, this_min))
+ timedelta(hours=4)
But there comes an error:
'str' object is not callable.
My desired output is the initial_datetime plus my time (in this case -7 hours ) and then add 4 hours. So, in my example, the new date should be '2015-11-03 05:05:22'.
datetime.combine is typically used to combine a date object with a time object rather than incrementing or decrementing a datetime object. In your case, you need to convert your datetime string to a datetime object and convert the parts of your time string to integers so you can add them to your datetime with timedelta. As an aside, be careful about using variable names, like time, that conflict with your imports.
from datetime import datetime, timedelta
dtstr = '2015-11-03 08:05:22'
tstr = '-7:00'
hours, minutes = [int(t) for t in tstr.split(':')]
dt = datetime.strptime(dtstr, '%Y-%m-%d %H:%M:%S') + timedelta(hours=hours+4, minutes=minutes)
print(dt)
# 2015-11-03 05:05:22

seconds since midnight to datetime (python)

I have a timezone aware datetime date object:
Timestamp('2004-03-29 00:00:00-0456', tz='America/New_York')
and a number of mili seconds since midnight (midnight in the local timezone):
34188542
How to combine them to get a valid datetime?
Create a timedelta object and add it to you time like this:
td = datetime.timedelta(milliseconds=34188542)
date_object = datetime.datetime.now() + td # change to your datetime object, I just use `now()`
Assuming the datetime object is ts, and by "combine them", you mean "add them":
ms = 34188545
new_datetime = ts + datetime.timedelta(milliseconds = ms)

Converting datetime to timedelta so they can be added

When subtracting two datetime objects, I understand the result is timedelta object:
import datetime
AcDepart = 1900-01-01 18:00:00
AcArrival = 1900-01-01 07:00:00
ActualHours = AcDepart - AcArrival
I want to then subtract the sum of two other date time objects from ActualHours
These are the two other objects:
HrsEarly = 1900-01-01 02:00:00
HrsLate = 1900-01-01 00:30:00
This is the equation that fails to complete:
UnCalcTime = ActualHours - (HrsEarly + HrsLate)
This is the error:
UnCalcTime = ActualHours - (HrsEarly + HrsLate)
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.datetime'
So, I obviously can't add datetime.datetime. Does anyone know how I could get around this? Can timedelta be added together? If so, how can I convert datetime to timedelta?
Any help would be greatly appreciated as I have been trying to solve this unsuccessfully for a long time.
The best solution is to create your variables as timedelta in the first place.
HrsEarly = datetime.timedelta(hours=2)
HrsLate = datetime.timedelta(minutes=30)
If you can't do that, you can simply subtract your "zero date" from the datetime objects.
>>> HrsEarly
datetime.datetime(1900, 1, 1, 2, 0)
>>> HrsEarly = HrsEarly - datetime.datetime(1900, 1, 1)
>>> HrsEarly
datetime.timedelta(0, 7200)
Convert the string to timedelta
from datetime import datetime
AcDepart = '1900-01-01 18:00:00'
AcDepart_ = datetime.strptime(AcDepart, '%Y-%m-%d %H:%M:%S')
AcArrival = '1900-01-01 07:00:00'
AcArrival_ = datetime.strptime(AcArrival, '%Y-%m-%d %H:%M:%S')
ActualHours = (AcDepart_ - AcArrival_).total_seconds()/3600
print ActualHours
It makes no sense to add two datetime objects: It might seem, in your example, that "2AM on the 1st of January 1900" plus "half past midnight on the 1st of January 1900" should be "half past two on the 1st of January 1900", but in another context the desired result could as easily be "half past two on the 2nd of February 3800", or even (if the UNIX epoch is used as an origin) "half past two on the first of January 1830".
Looking at a different example might make this more obvious: what should be the result of Tuesday + Saturday?
Your HrsEarly and HrsLate variables are presumably meant to store a time difference, and there's an appropriate type for that: datetime.timedelta. Adding two of those together does what you want:
>>> from datetime import timedelta
>>> HrsEarly = timedelta(hours=2)
>>> HrsLate = timedelta(minutes=30)
>>> HrsTotal = (HrsEarly + HrsLate)
>>> str(HrsTotal)
'2:30:00'
How about this method using built-in timestamp function?
import datetime
a = "2017-01-01 14:30:00"
b = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
c = b.timestamp()
d = datetime.timedelta(seconds=c)
Runtime environment
  OS: Ubuntu 16.04
  Python 3.6
Create a modules.py and paste the following two functions. Import them wherever you want and use as is.
import datetime
def JsTimestampToPyDatetime(js_date):
"""
converts javascript timestamp to python datetime taking care of
milliseconds and seconds
Args:
js_date(Timestamp, required)
Returns:
Datetime
"""
try:
# handles seconds
date = datetime.datetime.fromtimestamp(int(js_date))
except (ValueError):
# handles miliseconds
date = datetime.datetime.fromtimestamp(int(js_date) / 1000)
return date
# consuming javascript generated timestamps
a = JsTimestampToPyDatetime(1627303810000) # with miliseconds
b = JsTimestampToPyDatetime(1627476610) # with seconds only
def GetDaysInDateTime(min_stamp, max_stamp):
"""
Calculates time difference between two timestamps in days
Args:
min_stamp(Datetime, required): Minimum/start datetime
max_stamp(Datetime, required): Maximum/end datetime
Returns:
Int: Days
"""
days = (max_stamp-min_stamp).days
return int(days)
print(GetDaysInDateTime(a, b))

Categories

Resources