I have measurements taken from 1st January 1993. They were recorded in second elapsed from that date. I would like to have them in date time.
I know in MatLab the function would be
time = datenum(1993,01,01,00,00, time)
However, I struggle to find an equivalent function in Python.
I have tried:
datetime.fromordinal(time) doesn't work because 'module object has no attribute fromordinal'?
datetime.datetime(time) doesn't work (I have a matrix because there are many scans done)
https://docs.python.org/3/library/datetime.html
You will first have to create a datetime object for Jan 1st 1993 and then add the number of seconds to that date. The code below should help you get started.
from datetime import datetime, timedelta
original_date = datetime.strptime('01-01-1993', '%d-%m-%Y')
original_date + timedelta(seconds= 10000)
output: datetime.datetime(1993, 1, 1, 2, 46, 40)
Let us say you have list of timevalues in seconds starting from 1993-01-01 00:00.
Easiest would be:
datevec=[datetime.datetime(1993,1,1,0)+datetime.timedelta(seconds=val) for val in timevector]
It is like UNIX time, but with a different start.
You can compute the offset once:
>>> import datetime as dt
>>> dt.datetime(1993,1,1).timestamp()
725842800.0
and use it in your program:
OFFSET = 725842800.0
mydate = dt.datetime.fromtimestamp(OFFSET + seconds_from_1993)
Related
My code is the following:
date = datetime.datetime.now()- datetime.datetime.now()
print date
h, m , s = str(date).split(':')
When I print h the result is:
-1 day, 23
How do I get only the hour (the 23) from the substract using datetime?
Thanks.
If you subtract the current date from a past date, you would get a negative timedelta value.
You can get the seconds with td.seconds and corresponding hour value via just dividing by 3600.
from datetime import datetime
import time
date1 = datetime.now()
time.sleep(3)
date2 = datetime.now()
# timedelta object
td = date2 - date1
print(td.days, td.seconds // 3600, td.seconds)
# 0 0 3
You're not too far off but you should just ask your question as opposed to a question with a "real scenario" later as those are often two very different questions. That way you get an answer to your actual question.
All that said, rather than going through a lot of hoop-jumping with splitting the datetime object, assigning it to a variable which you then later use look for what you need in, it's better to just know what DateTime can do since that can be such a common part of your coding. You would also do well to look at timedelta (which is part of datetime) and if you use pandas, timestamp.
from datetime import datetime
date = datetime.now()
print(date)
print(date.hour)
I can get you the hour of datetime.datetime.now()
You could try indexing a list of a string of datetime.datetime.now():
print(list(str(datetime.datetime.now()))[11] + list(str(datetime.datetime.now()))[12])
Output (in my case when tested):
09
Hope I am of help!
This question seems obvious and easy but I am getting my head stretched out here. Problem is I have datetime field in model and I want to subtract time from another attribute.
here is my code I have tried so far.
#property
def boarding_time(self):
print('---------------------------')
time = self.schedule.travel_date_time.time()
print()
time_added = self.schedule.bus_company_route.routeboardingpoint_set.get(
point=self.boarding_point
).time_added
time1 = timedelta(hours=time.hour, minutes=time.minute, seconds=time.second)
time2 = timedelta(hours=time_added.hour, minutes=time_added.minute, seconds=time_added.second)
return (time1-time2)
I am actually trying to find the time delay the vehicle reaches to certain destination. Suppose vehicle was supposed to move at 8 am but the vehicle departed from bus park at 8:15 am and passenger waiting will have 15 min added to their location but I am getting error as
'datetime.timedelta' object has no attribute 'isoformat'
Im not sure if this answers your question but you can try:
from datetime import datetime, date
datetime.combine(date.today(), exit) - datetime.combine(date.today(), enter)
combine builds a datetime, that can be subtracted. Your can google about it for more...
https://docs.python.org/3/library/datetime.html
At a high level, the adjusted boarding time is derived from taking scheduled boarding time and adding to it the amount of time that lapsed between the scheduled departure time and the actual departure time from the previous destination.
Here is a simplified example that hopefully illustrates the key concepts to help you piece together a solution for your more complex problem:
from datetime import datetime, timedelta
scheduled_boarding_time = datetime.fromisoformat("2021-01-12T10:00")
departure_delay_in_minutes = 15
adjusted_boarding_time = scheduled_boarding_time + timedelta(minutes=delay_in_minutes)
print(adjusted_boarding_time.isoformat())
2021-01-12T10:15:00
The solution to your question lies in the way you handle the time stamp format. You have your date time in AM/PM for this you have to format you date accordingly. Here is something what you can do instead of what you are doing right now
from datetime import datetime
time = '2021/1/13 8:15 am' #your date format
time_added = '2021/1/13 8:45 am' #your date format
format = '%Y/%m/%d %H:%M %p' #will format your date for further computation
time = datetime.strptime(time, format)
time
o/p
datetime.datetime(2021, 1, 13, 8, 15)
time_added = datetime.strptime(time_added, format)
time_added
o/p
datetime.datetime(2021, 1, 13, 8, 45)
time2 = time_added-time1 # this will give you time difference in seconds
divmod(time2.total_seconds(), 60)[0] #use this to get difference in minutes
o/p
30.0
This same you return in your function and it will solve your problem
I am just wondering how best to approach using this 24 hour time format as a predictive feature. My thoughts were to bin it into 24 categories for each hour of the day. Is there an easy way to convert this object into a python datetime object that would make binning easier or how would you advise handling this feature? Thanks :)
df['Duration']
0 2:50
1 7:25
2 19:00
3 5:25
4 4:45
5 2:25
df['Duration'].dtype
dtype('O')
The best solution will depend on what you hope to get from your model. In many cases it makes sense to convert it to total number of seconds (or minutes or hours) since some epoch. To convert your data to seconds since 00:00, you can use:
from datetime import datetime
t_str = "2:50"
t_delta = datetime.strptime(t_str, "%H:%M") - datetime(1900, 1, 1)
seconds = t_delta.total_seconds()
hours = seconds/60**2
print(seconds)
# 10200.0
Using Python's datetime class will not support time values over 23:59. Since it appears that your data may actually be a duration, you may want to represent it as an instance of Python's timedelta class.
from datetime import timedelta
h, m = map(int, t_str.split(sep=':'))
t_delta = timedelta(hours=h, minutes=m)
# Get total number of seconds
seconds = t_delta.total_seconds()
You can use datetime to create a useable datetime string
>>> from datetime import datetime
>>> x = datetime(2019, 1, 1, 0).strftime('%Y-%m-%d %H:%M:%S')
>>> # Use that for your timestring then you can reverse it nicely back into a datetime object
>>> d = datetime.strptime('2019-01-01 00:00:00', '%Y-%m-%d %H:%M:%S')
Of course you can use any valid format string.
You should calculate the time in seconds or minutes or hours from some initial time like the 1st time. Then you can make an x-y scatter plot of the data since the x-axis (time) is now numbers.
I am using the following code to get the time:
import time
time = time.asctime()
print(time)
I end up with the following result:
'Tue Feb 25 12:09:09 2014'
How can I get Python to print just the hour?
You can use datetime:
>>> import datetime as dt
>>> dt.datetime.now().hour
9
Or, rather than now() you can use today():
>>> dt.datetime.today().hour
9
Then insert into any string desired:
>>> print('The hour is {} o\'clock'.format(dt.datetime.today().hour))
The hour is 9 o'clock
Note that datetime.today() and datetime.now() are both using your computer's notion of local time zone (ie, a 'naive' datetime object).
If you want to use time zone info, it is not so trivial. You can either be on Python 3.2+ and use datetime.timezone or use the third party pytz. I am assuming your computer's timezone is fine, and a naive (non time zone datetime object) is fairly easy to use.
import time
print (time.strftime("%H"))
time.asctime() will create a string, so extracting the hours part is hard. Instead, get a proper time.struct_time object, which exposes the components directly:
t = time.localtime() # gives you an actual struct_time object
h = t.tm_hour # gives you the hour part as an integer
print(h)
You can do it in one step if that's all you need the hour for:
print(time.localtime().tm_hour)
I was working on code to generate the time for an entire day with 30 second intervals. I tried using DT.datetime and DT.time but I always end up with either a datetime value or a timedelta value like (0,2970). Can someone please tell me how to do this.
So I need a list that has data like:
[00:00:00]
[00:00:01]
[00:00:02]
till [23:59:59] and needed to compare it against a datetime value like 6/23/2011 6:38:00 AM.
Thanks!
Is there a reason you want to use datetimes instead of just 3 for loops counting up? Similarly, do you want to do something fancy or do you want to just compare against the time? If you don't need to account for leap seconds or anything like that, just do it the easy way.
import datetime
now = datetime.datetime.now()
for h in xrange(24):
for m in xrange(60):
for s in xrange(60):
time_string = '%02d:%02d:%02d' % (h,m,s)
if time_string == now.strftime('%H:%m:%S'):
print 'you found it! %s' % time_string
Can you give any more info about why you are doing this? It seems like you would be much much better off parsing the datetimes or using strftime to get what you need instead of looping through 60*60*24 times.
There's a great answer on how to get a list of incremental values for seconds for a 24-hour day. I reused a part of it.
Note 1. I'm not sure how you're thinking of comparing time with datetime. Assuming that you're just going to compare the time part and extracting that.
Note 2. The time.strptime call expects a 12-hour AM/PM-based time, as in your example. Its result is then passed to time.strftime that returns a 24-hour-based time.
Here's what I think you're looking for:
my_time = '6/23/2011 6:38:00 AM' # time you defined
from datetime import datetime, timedelta
from time import strftime, strptime
now = datetime(2013, 1, 1, 0, 0, 0)
last = datetime(2013, 1, 1, 23, 59, 59)
delta = timedelta(seconds=1)
times = []
while now <= last:
times.append(now.strftime('%H:%M:%S'))
now += delta
twenty_four_hour_based_time = strftime('%H:%M:%S', strptime(my_time, '%m/%d/%Y %I:%M:%S %p'))
twenty_four_hour_based_time in times # returns True