substracting datetime object on date level - python

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

Related

Subtracting days from variable in date and time

I need to subtract 1 day from the current date and time? How would i do that?
Here is my code:
from datetime import datetime
now = datetime.now()
date = (now.strftime("%Y-%m-%d %H:%M:%S"))
print(date)
Say the date is (2021-10-3) i need the time variable to be set to something like (2021-10-2) Changing the day by -1 day!
Use timedelta.
from datetime import datetime, timedelta
now = datetime.now()
yesterday = now - timedelta(days=1)
date = (yesterday.strftime("%Y-%m-%d %H:%M:%S"))
print(date)
Find more about timedelta here

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

Adding timedelta object to datetime

My timedelta object looks like this: txdelta = 00:30:00. I want to add it to a datetime object but it consistently isn't working:
from datetime import datetime, date, time, timedelta
localdt = datetime.combine(datetime.strptime('2015-06-18', '%Y-%m-%d').date(),
(23:35:02+timedelta(txdelta)).time())
Note that the 23:35:02 is already a datetime object. I get this error message:
TypeError: unsupported type for timedelta days component: datetime.timedelta
What am I doing wrong?
The way you create your time object is strange. I strongly advice you to declare it this way if you're not used to it:
txdelta = timedelta(minutes=30)
tdelta = time(hour=1, minute=35, second=2)
If I got it well you tried to combine a date, a time and a timedelta. The full code below should do the trick:
from datetime import datetime, date, time, timedelta
txdelta = timedelta(minutes=30)
tdelta = time(hour=1, minute=35, second=2)
localdt = datetime.combine(datetime.strptime('2015-06-18', '%Y-%m-%d').date(), tdelta) + txdelta
print(localdt)
Basically, you combine a datetime object with a time one, and you simply add the timedelta object afterwards.
The output is:
2015-06-18 02:05:02

Convert local time to UNIX

I'm new to python and I'm trying to get the actual minutes passed every day since 7:00.
I am using mktime to get now_date1 and now_date2 in seconds, and then the plan it's to subtract and divide by 60 to get the minutes.
But I get the following error:
AttributeError: 'str' object has no attribute 'timetuple'
It's this the correct approach?
Here it's the code
import time
import pytz
from datetime import datetime
from time import mktime as mktime
now_date = datetime.now(pytz.timezone('Europe/Bucharest'))
now_date1 = now_date.strftime('%H:%M:%S')
now_date2 = now_date.strftime('7:00:00')
# Convert to Unix timestamp
d1_ts = time.mktime(now_date1.timetuple())
strftime returns a string. Not what you want.
You were pretty close, but there's no need to put time in the mix. Just modify your code like this and use time delta from datetime (inspired by How to calculate the time interval between two time strings):
import pytz
from datetime import datetime
now_date = datetime.now(pytz.timezone('Europe/Bucharest'))
from datetime import datetime
FMT = '%H:%M:%S'
now_date1 = now_date.strftime(FMT)
now_date2 = now_date.strftime('7:00:00')
tdelta = datetime.strptime(now_date1, FMT) - datetime.strptime(now_date2, FMT)
print(tdelta)
I get: 6:40:42 which seems to match since it's 12:42 here.
To get the result in minutes just do:
tdelta.seconds//60
(note that the dates have only correct hour/time/seconds, the year, month, etc.. are 1900 ... since they're not used)
I think something like this might work:
import time
import datetime
from time import mktime as mktime
#current time
now_date = datetime.datetime.now()
#time at 7am
today = datetime.date.today()
now_date2 = datetime.datetime(today.year, today.month, today.day, 7, 0, 0, 0)
#difference in minutes
(now_date - now_date2).days * 24 * 60

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.
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

Categories

Resources