I have a string in the following format
2021-05-06 17:30
How do I convert this to a python datetime and add a certain number of hours (e.g 4 hours)?
I also need to add a certain number of days to the string 2021-05-06
You can first parse the string to a datetime object, and then use a timedelta to add days, hours, etc. to the item.
from datetime import datetime, timedelta
dt = datetime.strptime('2021-05-06 17:30', '%Y-%m-%d %H:%M')
print(dt + timedelta(hours=4))
from datetime import datetime
from datetime import timedelta
origin_date = datetime.strptime("2021-05-06 17:30","%Y-%m-%d %H:%M")
three_hour_later = origin_date + timedelta(hours=3)
print(datetime.strftime(three_hour_later,"%Y-%m-%d %H:%M"))
Please check this link.
https://docs.python.org/3/library/datetime.html
Use the timedelta method available on datetime object to add days, hours, minutes or seconds to the date.
from datetime import datetime, timedelta
additional_hours = 4
additional_days = 2
old_date = datetime.strptime('2021-05-06 17:30', '%Y-%m-%d %H:%M')
new_date = old_date + timedelta(hours=additional_hours, days=additional_days)
print(new_date)
How can I extract the day of the week and the hour of the day from a timestamp in this format?
2020-08-17T01:54:38.000Z
So for the example above I would get Monday and 01 in return.
You could parse the string into a datetime object using strptime with a custom format, and then extract the info you need from it:
from datetime import datetime
dateStr = '2020-08-17T01:54:38.000Z'
dt = datetime.strptime(dateStr,'%Y-%m-%dT%H:%M:%S.%fZ')
hour = dt.strftime('%H')
dayOfWeek = dt.strftime('%A')
'I'm trying to subtract a day from this date 1590074712 in order to make 1590008151 but can't figure out any way to achieve that.
I've tried with:
from datetime import datetime
ts= 1590074712
date = datetime.timestamp(ts) - timedelta(days = 1)
print(date)
How can I subtract a day from a date in the above format?
I want the output in timestamp
Use datetime.fromtimestamp():
from datetime import datetime, timedelta
ts= 1590074712
date = datetime.fromtimestamp(ts) - timedelta(days = 1)
print(date)
Prints:
2020-05-20 15:25:12
I want to get the 20th of previous month, given the current_date()
I am trying to use time.strftime but not able to subtract the value from it.
timestr = time.strftime("%Y-(%m-1)%d")
This is giving me error. The expected output is 2019-03-20 if my current_date is in April. Not sure how to go about it.
I read the posts from SO and most of them address getting the first day / last day of the month. Any help would be appreciated.
from datetime import date, timedelta
today = date.today()
last_day_prev_month = today - timedelta(days=today.day)
twenty_prev_month = last_day_prev_month.replace(day=20)
print(twenty_prev_month) # 2019-03-20
Use datetime.replace
import datetime
current_date = datetime.date.today()
new_date = current_date.replace(
month = current_date.month - 1,
day = 20
)
print(new_date)
#2019-03-20
Edit
That won't work for Jan so this is a workaround:
import datetime
current_date = datetime.date(2019, 2, 17)
month = current_date.month - 1
year = current_date.year
if not month:
month, year = 12, year - 1
new_date = datetime.date(year=year, month=month, day=20)
I imagine it is the way dates are parsed. It is my understanding that with your code it is looking for
2019-(03-1)20 or 2019-(12-1)15, etc..
Because the %y is not a variable, but a message about how the date is to be expected within a string of text, and other characters are what should be expected, but not processed (like "-")
This seems entirely not what you are going for. I would just parse the date like normal and then reformat it to be a month earlier:
import datetime
time = datetime.datetime.today()
print(time)
timestr = time.strftime("%Y-%m-%d")
year, month, day = timestr.split("-")
print("{}-{}-{}".format(year, int(month)-1, day))
This would be easier with timedelta objects, but sadly there isn't one for months, because they are of various lengths.
To be more robust if a new year is involved:
import datetime
time = datetime.datetime.today()
print(time)
timestr = time.strftime("%Y-%m-%d")
year, month, day = timestr.split("-")
if month in [1, "01", "1"]: # I don't remember how January is represented
print("{}-{}-{}".format(int(year) - 1, 12, day)) # use December of last year
else:
print("{}-{}-{}".format(year, int(month)-1, day))
This will help:
from datetime import date, timedelta
dt = date.today() - timedelta(30)// timedelta(days No.)
print('Current Date :',date.today())
print(dt)
It is not possible to do math inside a string passed to time.strftime, but you can do something similar to what you're asking very easily using the time module
in Python 3
# Last month
t = time.gmtime()
print(f"{t.tm_year}-{t.tm_mon-1}-20")
or in Python 2
print("{0}-{1}-{2}".format(t.tm_year, t.tm_mon -1, 20))
If you have fewer constraints, you can just use the datetime module instead.
You could use datetime, dateutil or arrow to find the 20th day of the previous month. See examples below.
Using datetime:
from datetime import date
d = date.today()
month, year = (d.month-1, d.year) if d.month != 1 else (12, d.year-1)
last_month = d.replace(day=20, month=month, year=year)
print(last_month)
Using datetime and timedelta:
from datetime import date
from datetime import timedelta
d = date.today()
last_month = (d - timedelta(days=d.day)).replace(day=20)
print(last_month)
Using datetime and dateutil:
from datetime import date
from dateutil.relativedelta import relativedelta # pip install python-dateutil
d = date.today()
last_month = d.replace(day=20) - relativedelta(months=1)
print(last_month)
Using arrow:
import arrow # pip install arrow
d = arrow.now()
last_month = d.shift(months=-1).replace(day=20).datetime.date()
print(last_month)
In my task what I need to do is to subtract some hours and minutes like (0:20,1:10...any value) from time (2:34 PM) and on the output side I need to display the time after subtraction.
time and hh:mm value are hardcoded
Ex:
my_time = 1:05 AM
duration = 0:50
so output should be 12:15 PM
Output should be exact and in AM/PM Format and Applicable for all values
(0:00 < Duration > 6:00) .
I don't care about seconds, I only need the hours and minutes.
from datetime import datetime, timedelta
d = datetime.today() - timedelta(hours=0, minutes=50)
d.strftime('%H:%M %p')
This worked for me :
from datetime import datetime
s1 = '10:04:00'
s2 = '11:03:11' # for example
format = '%H:%M:%S'
time = datetime.strptime(s2, format) - datetime.strptime(s1, format)
print time
from datetime import datetime
d1 = datetime.strptime("01:05:00.000", "%H:%M:%S.%f")
d2 = datetime.strptime("00:50:00.000", "%H:%M:%S.%f")
print (d1-d2)