I am looking for a comparison of two times in Python. One time is the real time from computer and the other time is stored in a string formatted like "01:23:00".
import time
ctime = time.strptime("%H:%M:%S") # this always takes system time
time2 = "08:00:00"
if (ctime > time2):
print("foo")
import datetime
now = datetime.datetime.now()
my_time_string = "01:20:33"
my_datetime = datetime.datetime.strptime(my_time_string, "%H:%M:%S")
# I am supposing that the date must be the same as now
my_datetime = now.replace(hour=my_datetime.time().hour, minute=my_datetime.time().minute, second=my_datetime.time().second, microsecond=0)
if (now > my_datetime):
print("Hello")
EDIT:
The above solution was not taking into account leap second days (23:59:60). Below is an updated version that deals with such cases:
import datetime
import calendar
import time
now = datetime.datetime.now()
my_time_string = "23:59:60" # leap second
my_time_string = now.strftime("%Y-%m-%d") + " " + my_time_string # I am supposing the date must be the same as now
my_time = time.strptime(my_time_string, "%Y-%m-%d %H:%M:%S")
my_datetime = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=calendar.timegm(my_time))
if (now > my_datetime):
print("Foo")
https://docs.python.org/2/library/datetime.html
The datetime module will parse dates, times, or combined date-time values into objects that can be compared.
from datetime import datetime
current_time = datetime.strftime(datetime.utcnow(),"%H:%M:%S") #output: 11:12:12
mytime = "10:12:34"
if current_time > mytime:
print "Time has passed."
Related
I am trying to pull events from an ics file within the next month but making my own datetime and comparing to the datetime in the ics file doesn't seem to be working and is giving the error TypeError: can't compare offset-naive and offset-aware datetimes
I tried the answers found here but still get the same error. Below is the code I am using.
def read_from_cal():
g = open('calendar.ics', 'rb')
gcal = Calendar.from_ical(g.read())
year = datetime.now().year
month = datetime.now().month
day = datetime.now().day
hour = datetime.now().strftime("%H")
minute = datetime.now().strftime("%M")
next_month = datetime(int(year), int(month)+1, int(day), int(hour), int(minute), 0, tzinfo=pytz.UTC)
#next_month = next_month.replace(tzinfo=pytz.UTC)
for component in gcal.walk():
if component.name == "VEVENT":
# time printed out in format:
# year-month-day hour:min:sec
summ = component.get('summary')
start = component.get('dtstart').dt
end = component.get('dtend').dt
if now <= start <= next_month:
print("Worked")
print(summ, start, end)
I've tried both with using replace to change my time to utc and just putting it in the next_month variable itself and they both give the same error above.
I've also tried this and this to no avail.
I have tried with a .ics file generated here, so could not be the same problem, but in some cases start is a datetime.datetime and in other cases is a datetime.date.
This solution worked with my .ics file
from icalendar import Calendar
from datetime import datetime
from dateutil.relativedelta import relativedelta
def read_from_cal():
g = open('example.ics', 'rb')
gcal = Calendar.from_ical(g.read())
today = datetime.now()
next_month = today + relativedelta(months=1)
for component in gcal.walk():
if component.name == "VEVENT":
summ = component.get('summary')
start = component.get('dtstart').dt
end = component.get('dtend').dt
if isinstance(start, datetime):
start = start.replace(tzinfo=None)
if start <= next_month:
print("Worked (datetime)")
print(summ, start, end)
else:
# some events are stored as a date
if start <= next_month.date():
print("Worked (date)")
print(summ, start, end)
read_from_cal()
I'm working in small test code to determine if a generated datetime is before or after the midday like the code below.
import random
from datetime import datetime, timedelta
from pytz import timezone
current_date = datetime.now(timezone('America/Sao_Paulo'))
new_date = current_date - timedelta(days=2)
print (new_date.strftime("%Y-%m-%d %H:%M:%S"))
while new_date <= current_date:
new_date = new_date + timedelta(minutes=10)
print (new_date.strftime("%Y-%m-%d %H:%M:%S"))
if new_date < datetime.time(12):
print("test")
The problem is, I can't verify if the new_date is under the midday. Probably I'm doing something wrong in the if condition, right?
I would like to print some results if the new_dateis after midday and another message if it's after midday to midnight.
Any suggestions how I can solve this?
You need to compare just the time from new_date, with 12 converted to a datetime object.
Because of the way you did the imports, when you use datetime.time() it means you are calling datetime.datetime.time() and not datetime.time(), which is why the conversion fails.
You can solve this by
from datetime import datetime, timedelta, time
and then use
time()
or by
import datetime as dt
then using in the appropriate places
dt.datetime(), dt.timedelta(), dt.time()
Complete code:
import random
from datetime import datetime, timedelta, time
from pytz import timezone
current_date = datetime.now(timezone('America/Sao_Paulo'))
new_date = current_date - timedelta(days=2)
print (new_date.strftime("%Y-%m-%d %H:%M:%S"))
while new_date <= current_date:
new_date = new_date + timedelta(minutes=10)
print (new_date.strftime("%Y-%m-%d %H:%M:%S"))
if new_date.time() < time(12):
print("test")
Compare to new_date.hour, instead of datetime.time()
import random
from datetime import datetime, timedelta
from pytz import timezone
current_date = datetime.now(timezone('America/Sao_Paulo'))
new_date = current_date - timedelta(days=2)
print (new_date.strftime("%Y-%m-%d %H:%M:%S"))
while new_date <= current_date:
new_date = new_date + timedelta(minutes=10)
print (new_date.strftime("%Y-%m-%d %H:%M:%S"))
if new_date.hour < 12:
print("before noon")
elif new_date.hour >= 18:
print("after 6 pm")
I am trying to add seconds to a datestamp string that is received from a json object but the datetime function I am trying to use does not allow strings and wants the date to be separated like: datetime.strftime(2011,11,18). Here is what I have:
import requests
from datetime import datetime
def call():
pay = {'token' : "802ba928cd3ce9acd90595df2853ee2b"}
r = requests.post('http://challenge.code2040.org/api/dating',
params=pay)
response = r.json()
time = response['datestamp']
interval = response['interval']
utc = datetime.strftime(time, '%Y-%m-%dT&H:%M:%S.%fZ')
timestamp = (utc-time).total_seconds()
utc_dt = datetime(time) + timedelta(seconds=timestamp)
print(utc_dt.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
Is there another way I can add time to a ISO8601 datestamp?
I have imported the following modules at the top of my python script:
import os
import sys
import time
import datetime
import random
import pprint
from random import randint
from time import sleep
from datetime import datetime, timedelta
But, I am still getting a module object error for this part of my code:
def check(low,high):
with open('done.txt', 'r+') as done:
ts = time.time()
sttime = datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ')
done_completed = open('done_completed.txt', "a")
for line in done:
now = datetime.now()
now_time = now.time()
if now_time >= time(23,30) and now_time <= time(06,30):
print "sleeping"
sleep(5000)
else:
done_id = line.strip()[20:]
then = datetime.strptime(line.strip()[:17], '%Y%m%d_%H:%M:%S')
(There's another if elif elif under all that but I figured it isn't relevant to the error)
(Yes, I am a python beginner)
The error is:
File "/home/joe/Desktop/follomatic/follomatic.py", line 85, in check
if now_time >= time(23,30) and now_time <= time(06,30):
TypeError: 'module' object is not callable
Does anyone see what is wrong? Have I not specified to call the module in the right way?
Thanks :)
Python's datetime module is a bit of a rat's nest. :) And it can get even more confusing if you use from imports.
This code should clarify things a bit. Note that this is not a great way to do things. It's generally better to work with datetime.datetime objects rather than datetime.time objects, otherwise things get messy if you need to handle time intervals that include midnight (or multiple days). But I wrote this code to roughly correspond with the code in your question, and I wanted to make it easy to test at any time of day.
#!/usr/bin/env python
''' datetime.time manipulation demo
From http://stackoverflow.com/q/28605732/4014959
Written by PM 2Ring 2015.02.19
'''
from time import sleep
import datetime
now = datetime.datetime.now()
now_time = now.time()
#A datetime.time example
t1 = datetime.time(5, 30)
print 't1 is', t1
now = datetime.datetime.now()
now_time = now.time()
print 'now is %s, now_time is %s' % (now, now_time)
begin_datetime = now + datetime.timedelta(seconds=5)
end_datetime = now + datetime.timedelta(seconds=10)
begin_time = begin_datetime.time()
end_time = end_datetime.time()
print 'begin', begin_time
print 'end', end_time
for i in xrange(15):
now_time = datetime.datetime.now().time()
print now_time, begin_time <= now_time <= end_time
sleep(1)
typical output
t1 is 05:30:00
now is 2015-02-19 23:44:39.152786, now_time is 23:44:39.152786
begin 23:44:44.152786
end 23:44:49.152786
23:44:39.152905 False
23:44:40.153999 False
23:44:41.155191 False
23:44:42.156398 False
23:44:43.156614 False
23:44:44.157810 True
23:44:45.159028 True
23:44:46.160231 True
23:44:47.161444 True
23:44:48.162660 True
23:44:49.163869 False
23:44:50.165076 False
23:44:51.166650 False
23:44:52.167842 False
23:44:53.169053 False
I'm trying to make a scheduler to run scripts at certain times.
The code below is my own version, but there is a problem with when the time gets to 23:59:59 and goes across to 00:00:01 it for some reason doesn't continue idling... instead it calls the callscripts() once and then it will go back to idling...
from datetime import date, timedelta
from sched import scheduler
from time import time, sleep, strftime
import random
s = scheduler(time, sleep)
random.seed()
def periodically(runtime, intsmall, intlarge, function):
## Get current time
currenttime = strftime('%H:%M:%S')
## If currenttime is anywhere between 23:40 and 23:50 then...
if currenttime > '23:40:00' and currenttime < '23:50:00':
## Call clear
clear()
## Update time
currenttime = strftime('%H:%M:%S')
## Idle time
while currenttime > '23:40:00' and currenttime < '23:59:59' or currenttime > '00:00:00' and currenttime < '01:30:00':
## Update time
currenttime = strftime('%H:%M:%S')
runtime += random.randrange(intsmall, intlarge)
s.enter(runtime, 1, function, ())
s.run()
def callscripts():
print "Calling Functions"
main1()
main2()
def main1():
print "Main1"
def main2():
print "Main2"
def clear():
print "Clearing"
while True:
periodically(2, -1, +1, callscripts)
Anyone know how this can be fixed or know a better way to do this?
Many thanks AEA
This is just a concept on how you could go about things more efficiently than using strings.
import time, calendar
# Get the current time in a localtime manner (we need it for the day and year)
today = time.localtime(time.time())
# We put the day, month and year into a strftime -> localtime converter
# giving us the localtime version of 00:00:00 of today (there's cleaner version for this process)
today_strftime = time.strptime(str(today.tm_mday) + " " + time.strftime("%b") + " " + str(today.tm_year)[-2:], "%d %b %y")
# Then we take that localtime of 00:00:00 and put it into timegm which gives us the unix
# timestamp of 00:00:00 today, which we can subtract from time.time() to give us how many
# seconds of today has passed since 00:00:00.. Which we can use to compare integers with eachother (more efficient, and easy to compare)
unixtime_beginning_of_day = calendar.timegm(today_strftime)
time_passed_today = time.time() - unixtime_beginning_of_day
if time_passed_today > 3600:
# 60sec per min * 60 minutes per hour == 3600 seconds in one hour.
print "One hour has passed since the start of this day"