I want to get the date time object for last hour.
Lets say the sys time is "2011-9-28 06:11:30"
I want to get the output as "2011-9-28 05" #{06 - 1 hour}
I used:
lastHourDateTime = date.today() - timedelta(hours = 1)
print lastHourDateTime.strftime('%Y-%m-%d %H:%M:%S')
However, my output is not showing the time part at all. where am I going wrong?
Date doesn't have the hour - use datetime:
from datetime import datetime, timedelta
last_hour_date_time = datetime.now() - timedelta(hours = 1)
print(last_hour_date_time.strftime('%Y-%m-%d %H:%M:%S'))
This works for me:
import datetime
lastHourDateTime = datetime.datetime.now() - datetime.timedelta(hours = 1)
print(lastHourDateTime.strftime('%Y-%m-%d %H'))
# prints "2011-09-28 12" which is the time one hour ago in Central Europe
You can achieve the same goal using pandas:
import pandas as pd
pd.Timestamp.now() - pd.Timedelta('1 hours')
Related
I would like to know how many days are passed from a x ago to today
I wrote this:
from datetime import datetime
timestamp = 1629195530 # A month ago
before = datetime.fromtimestamp(timestamp)
daysBefore = before.strftime("%d")
now = datetime.now()
today = now.strftime("%d")
print(f"daysBefore {daysBefore} - today {today}")
daysPassed = int(today) - int(daysBefore)
But so it seems, daysBefore is returning the days of the month, I can't get my head around this :(
Exact format with date time hour minute accuracy
from datetime import datetime
timestamp = 1629195530 # A month ago
before = datetime.fromtimestamp(timestamp)
now = datetime.now()
print(now - before))
print(f"daysBefore {daysBefore} - today {today}")
The reason this doesn't work is that it gives the day of the month. For example 17th of July and 17th of August will give a difference of zero days.
Therefore the recommend method is as #abdul Niyas P M says, use the whole date.time format to subtract two dates and afterwards extract the days.
Your issue is due to this: strftime("%d")
You are converting you date to a string and then to an int to make the difference. You can just use the datetime to do this for you:
timestamp = 1629195530 # A month ago
before = datetime.fromtimestamp(timestamp)
now = datetime.now()
print(f"daysBefore {before} - today {now}")
daysPassed = now - before
print(daysPassed.days)
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)
I have a time from five minutes ago, using datetime.time.now() and I need to know what the time would be if I subtracted that time from the current time.
Try 1 - Didn't Work:
from datetime import datetime, timedelta
time1 = datetime.now()
time2 = datetime.now() + timedelta(minutes=5)
print(time1 - time2)
This gave me "-1 day, 23:54:59.999987".
Try 2 - Worked, but is there a better way?:
time1 = datetime.now()
time2 = datetime.now() + timedelta(minutes=5)
print(str(time1 - time2).split(',')[1])
This gave me the desired result, but is there a method besides string manipulation?
You wanted to take an advice how to use a time object?
Well, if you want to specify a format of string representation of your time, just use strftime
Example below:
from datetime import datetime, timedelta
time1 = datetime.now()
time2 = datetime.now() + timedelta(minutes=5)
print((time1 - time2).strftime('%H:%M:%S'))
Assuming you want the time 5 minutes ago, you can use timedelta without any string manipulation:
five_min_ago = datetime.datetime.now() - datetime.timedelta(minutes = 5)
I can get current time in milliseconds as follows:
import time
timestamp = int(time.time()*1000.0)
However, how can I get the milliseconds of the beginning of today, e.g. 09/09/2018 00:00 ?
import pandas as pd
import datetime
int(pd.to_datetime(datetime.datetime.now().date()).value / 1000000)
# Outputs: 1536451200000
I hope this works to get the required start of the date's time in milliseconds in Python 3
from datetime import datetime
dt_obj = datetime.strptime('09.09.2019 00:00',
'%d.%m.%Y %H:%M')
millisec = dt_obj.timestamp() * 1000
print(millisec)
Output>> 1568001600000.0
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