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")
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()
can please anyone helps me with my code?
this is the error that I got
I just don't get it on how did I get this error:
CurrentDate = datetime.datetime.strptime(CurrentDate, "%Y-%m-%d %H:%M")
TypeError: strptime() argument 1 must be str, not datetime.date
Full code:
import datetime
CurrentDate = datetime.datetime.now().date()
print(CurrentDate)
Run4Start = str(CurrentDate) + " 16:00"
Run4End = str(CurrentDate) + " 20:00"
Run4Start = datetime.datetime.strptime(Run4Start, "%Y-%m-%d %H:%M")
Run4End = datetime.datetime.strptime(Run4End, "%Y-%m-%d %H:%M")
print("RUN4 :", CurrentDate )
print(Run4Start, Run4End)
CurrentDate = datetime.datetime.strptime(CurrentDate, "%Y-%m-%d %H:%M")
print(CurrentDate)
if CurrentDate >= Run4Start and CurrentDate <= Run4End:
print("Hit")
else:
print("Miss!")
In:
CurrentDate = datetime.datetime.strptime(CurrentDate, "%Y-%m-%d %H:%M")
CurrentDate is already a datetime.date object, created above:
CurrentDate = datetime.datetime.now().date()
and never changed to anything else. So you don't need to parse it, it's already "parsed". Just remove the line attempting to parse it.
That said, it's just a date, and you're comparing it to datetimes on a specific day; whether or not it works, it won't do what you're probably trying to do (determine if the current time is between 1600 and 2000). You don't need string parsing to do that at all; your entire block of code testing for a hit vs. miss could simplify to:
if datetime.time(16) <= datetime.datetime.now().time() <= datetime.time(20):
print("Hit")
else:
print("Miss!")
since you only care about the time component, not the date component at all.
I'm doing a parse from string ISO8601 to a datetime and it's working. Now I want to return datetime on localtime but my code is returning same timestamp from input:
def format_string_to_timestamp(dt, defaultTimezone='America/Sao_Paulo'):
origin_dt = datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S.%f')
tz_local = pytz.timezone (defaultTimezone)
dt_local = origin_dt.astimezone(tz_local).replace(tzinfo=None)
print(dt)
print(dt_local)
print(origin_dt)
return dt_local.strftime('%Y-%m-%d %H:%M:%S')
# example input: 2019-02-25T17:58:53.753
What is missing to return dt_local as America/Sao_Paulo timezone?
I have the input date of 2017-08-22T11:32:31+10:00
I wish to convert this to UTC which would be 2017-08-22+01:32:31
Code so far
from datetime import datetime, timedelta
from pytz import timezone
import pytz
fmt = "%Y-%m-%d+%H:%M:%S"
now_time = datetime('2017-08-22T11:32:31+10:00')
zone = 'UTC'
now_time = now_time.timezone(zone)
print now_time.strftime(fmt)
Error
now_time = datetime('2017-08-22T11:32:31+10:00')
TypeError: an integer is required
You can use dateutil.parser to infer the datetime format when creating your datetime object.
import dateutil.parser
your_date = dateutil.parser.parse('2017-08-22T11:32:31+10:00')
Next, you can use the .astimezone function to convert your_date to UTC:
utc_date = your_date.astimezone(pytz.utc)
print(utc_date)
Output:
2017-08-22 01:32:31+00:00
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."