Time = datetime.datetime.now().time()
I wanted to find the difference in seconds between the Time above^ and the hour of the day:
for example if the Time = 15:07:25.097519, so the hour of the day is 15:00:00, i want to store 445.097519 seconds to a variable.
How can I do that?
I am an amateur at this please help!!
import datetime
now = datetime.datetime.now()
hour = now.replace(minute=0, second=0, microsecond=0)
seconds = (now - hour).seconds + (now - hour).microseconds / 1000000
Here is one way to do it. Extract the hour from current time, and initialize a new datetime.time object with hour as input. Then you convert both of the timestamps to datetime and then do the subtraction. Code below does that
Time = datetime.datetime.now().time()
hour = str(Time).split(":")[0]
currentHourTime = datetime.datetime(2019,10,31,int(hour),0,0,0).time()
dateTimeCurr = datetime.datetime.combine(datetime.date.today(), Time)
dateTimeCurrHour = datetime.datetime.combine(datetime.date.today(), currentHourTime)
dateTimeDifference = dateTimeCurr - dateTimeCurrHour
dateTimeDifferenceInSeconds = dateTimeDifference.total_seconds()
print(dateTimeDifferenceInSeconds)
Related
Hopefully just a simple question. I want to convert a datetime object to seconds and include the days. I've just noticed that my code skipped the day. Please note times are just an example and not 100% accurate.
Content of oldtime.txt (2 days ago):
2021-09-16 19:34:33.569827
Code:
oldtimefile = open('oldtime.txt', 'r+')
oldtme = oldtimefile.read()
datetimeobj = datetime.strptime(oldtme, "%Y-%m-%d %H:%M:%S.%f")
finaltime = datetime.now() - datetimeobj
print(finaltime.seconds)
If I just print finaltime then I get 1 day, 22:13:30.231916.
Now if we take today's date and time - just for argument sake - (2021-09-18 17:34:33.569827) as now then I actually get 80010 seconds instead of roughly 172800 seconds. It's ignoring the day part.
How can I include the day and convert the entire object to seconds?
Thanks.
Instead of .seconds you can use .total_seconds():
from datetime import datetime
oldtme = "2021-09-16 19:34:33.569827"
datetimeobj = datetime.strptime(oldtme, "%Y-%m-%d %H:%M:%S.%f")
finaltime = datetime.now() - datetimeobj
print(finaltime.total_seconds())
Prints:
164254.768354
I am currently retrieving a date in the format of 2020-09-23T09:03:46.242Z (YYYY-MM-DDThh:mm:ss.sssZ) and I am trying to convert it into Wed Sep 23 09:03:46 2020. Struggling with the string manipulations, does anyone have any ideas?
Essentially my goal is to be able to perform os.time() on the date, but im aware I may need to do some reformatting beforehand.
Any help is greatly appreciated
Thanks, Scott.
local s = '2020-09-23T09:03:46.242Z'
local t = {}
t.year, t.month, t.day, t.hour, t.min, t.sec =
assert(s:match'^(%d+)%-(%d+)%-(%d+)T(%d+):(%d+):(%d+)')
print(os.date('%c', os.time(t)))
Try this:
local function convert (s)
local source_format = '(%d%d%d%d)-(%d%d)-(%d%d)T(%d%d):(%d%d):(%d%d)%.'
local year, month, day, hour, min, sec = string.match( s, source_format )
local unix_time = os.time {
year = tonumber(year),
month = tonumber(month),
day = tonumber(day),
hour = tonumber(hour),
min = tonumber(min),
sec = tonumber(sec)
}
local target_format = '%a %b %d %H:%M:%S %Y'
return os.date( target_format, unix_time )
end
I want to print the amount of days, hours, minutes and seconds until christmas day but when it prints, it also gives me the millisecond. I tried doing print(remain_until_xmas.strip(.) but that didn't work. Here is the code
import datetime as dt
xmas = dt.datetime(2020, 12, 25)
now = dt.datetime.now()
until_xmas = xmas - now
print(until_xmas)
To get the time live, you can use this code:
import time
time = str(time.strftime("%M")) + ":" + str(time.strftime("%S"))
print(time)
This will give you the current time in Minutes and Seconds, and if you put it in a loop, it will keep updating itself.
If you want the day and month, you can use
print(time.strftime("%A, %B %e")) -
With this code, you can then subtract the Xmas date from the current date, and retrieve what you want.
This would be your final code:
import time
month = time.strftime("%m")
day = time.strftime("%d")
hour = time.strftime("%H")
minute = time.strftime("%M")
second = time.strftime("%S")
chrmonth = 12
chrday = 23
chrhour = 12
chrminute = 60
chrsecond = 60
print("The time until christmas is, ", int(chrmonth) - int(month), "months", int(chrday) - int(day), "days", int(chrhour) - int(hour), "hours", int(chrminute) - int(minute), "minutes", int(chrsecond) - int(second), "seconds")
Hopefully this helps!
you can use .strftime()
print(until_xmas.strftime("%m/%d/%Y, %H:%M:%S"))
see more here about strftime.
I have a csv file with date and time. I want to give specific timeinterval (60min) in between time range (start time and end time). I wrote a code with a date. But it gives me an error Number of samples, -5, must be non-negative. Then I checked with separate csv file with less data. Then I found that I have time like 9:53 , 10:20 ,11:42 .... Then when I'm dividing to find num_periods then its give me an error.
example
take date range like
2018 /8/6 start time is 6:00
2018/8/6 end time is 23:52
then it between I have time like 7:00, 8:52,10:42 so on.
after that in next day I have a time period like this.
So when I tried to find a num_periods then it give me this error.
I want to specify time in between this time_range
(start_time+time_interval(3600 in seconds (60min)) in between time_range)
Can anyone give me solution for this?
my code is,
time_interval = 3600
date_array = []
date_array.append(pd.to_datetime(data['date'][0]).date())
start_time = []
end_time = []
temp_date = pd.to_datetime(data['date'][0]).date()
start_time.append(pd.to_datetime(data['time'][0], format='%H:%M:%S').time())
for i in range(len(data['date'])):
cur_date = pd.to_datetime(data['date'][i]).date()
if( cur_date > temp_date):
end_time.append(pd.to_datetime(data['time'][i-1], format='%H:%M:%S').time())
start_time.append(pd.to_datetime(data['time'][i], format='%H:%M:%S').time())
date_array.append(cur_date)
temp_date = cur_date
end_time.append(pd.to_datetime(data['time'][len(data['date'])-1], format='%H:%M:%S').time())
datetime_array = []
for i in range(len(date_array)):
s_time = datetime.datetime.combine(date_array[i],start_time[i])
e_time = datetime.datetime.combine(date_array[i], end_time[i])
timediff = (e_time - s_time)
num_periods = int(timediff.total_seconds()/time_interval) +1
time_list = pd.date_range(start=s_time, end = e_time, periods=num_periods ).to_pydatetime()
datetime_array.extend(time_list)
error:
subset of my csv file
It looks like num_periods is negative:
num_periods = int(timediff.total_seconds()/time_interval) + 1
the easiest solution is to take the abs value instead:
num_periods = abs(int(timediff.total_seconds()/time_interval)) + 1
Note: that date_range supports ranges in reverse order (where start > end).
def waktusekarang
SimpleDateFormat abc = new SimpleDateFormat("HHmm")
waktusekarang = abc.format(new Date())
if current time is 13:58, then it will be become 1358 because (SimpleDateFormat is HHmm). then how to +2 minutes to the current time then the result become 1400.
i try new Date()+2 but its not success and the result become 13581,and i also try to parseInteger but its not success too.
please help my problem , how can i +1 or +2 minutes to current time if current minute is 59.because if minute is 59 then +1 will be 60 ,it must be 00
Use can use Calendar to add minutes to your time, appropriately your time would be incremented:
SimpleDateFormat abc = new SimpleDateFormat("HHmm");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 2);
String waktusekarang = abc.format(cal.getTime());
System.out.println(waktusekarang);
A Groovy solution would be:
Date in2mins = use( groovy.time.TimeCategory ) {
new Date() + 2.minutes
}
String waktusekarang = in2mins.format( 'HHmm' )
println waktusekarang
Dont use format(Date). Use format(int) and then call System.currentTimeMillis() and add 120000 ms = 2 mins. Thats a way to do it without calendar. But you should think of using calendar.
SimpleDateFormat abc = new SimpleDateFormat("HHmm");
waktusekarang = abc.format(System.currentTimeMillis()+120000);