Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
What would a piece of code look like which checks today's date, and if it's a particular date, it will print out a message?
The context is that I'm making a birthday cake for my son who codes and I want to write a themed Happy Birthday message on top correctly. (Sorry, not as clever or serious as a lot of the things on here!)
I'd like something which is basically:
johnsBirthday = 01/01/1998
johnsAge = todaysdate - johnsBirthday (in years)
if todays date == 01/01/XXXX then print("Happy Birthday John!" + johnsAge + " today!")
My knowledge of python is very limited (as I'm sure you can tell from the above) but I vaguely know how to do this in Excel, so I figure there must be a way to do it in python too?
I know could always just write out:
print("Happy Birthday, John!")
and he'd appreciate that, but I think it would really make him smile to go a little further than that!
# Import datetime class from datetime module
from datetime import datetime
birthday = "20/09/1998"
# Parses the string into a datetime object
birthday_obj = datetime.strptime(birthday, '%d/%m/%Y')
# Gets todays date
now = datetime.now()
# Checks the day and month to verify birthday status
if(birthday_obj.day == now.day and birthday_obj.month == now.month):
johns_age = str(now.year - birthday_obj.year)
print("Happy Birthday John! " + johns_age + " today!")
For your purpose, it might be easier to use regular expressions if you are familiar with them. You can search any patterns you like, after converting datetimes to string, or better yet if you already have datetimes in string formats.
For datetime to string format conversion codes, check out -
format-codes
Example code
import re
from datetime import datetime
pattern = re.compile(r'^01/01/')
today_date = datetime.now().strftime(r'%d/%m/%Y')
some_date = '01/01/2021'
print(re.match(pattern, some_date)) # <re.Match object; span=(0, 6), match='01/01/'>
print(today_date) # 20/09/2020
print(pattern.match(today_date)) # None
Edit - Had forgotten that age needs to be calculated!
import re
from datetime import datetime
johns_birthday = '01/01/1998'
if (re.match('^01/01/', johns_birthday)):
johns_age = datetime.now().year - datetime.strptime(johns_birthday, r'%d/%m/%Y').year
print("Happy Birthday John! " + str(johns_age) + " today!")
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I need a function returning a boolean indicating if midnight has just passed.
I came up with this but I am not happy with the "form". Can anyone think of anything better? as in terms of efficiency/elegance?
from datetime import datetime, timedelta
def passed_midnight(delta=1):
time_now = datetime.today # see other comment below
time_ago = time_now() - timedelta(minutes=delta)
# next line with a dummy delta (zero) cuz "datetime.today - timedelta(days=1)" gives an error
today = time_now() - timedelta(days=0)
return today.strftime("%Y%m%d") != time_ago.strftime("%Y%m%d")
>>> print(passed_midnight, 10)
datetime.today - timedelta(days=1) gives an error because datetime.today is a function that needs to be called. This is why you must have felt the need to write time_now() with parentheses: it's calling the function, twice (with different results, because time has a tendency to pass).
Avoid strftime in favour of date(), which returns the date part only (as a datetime.date object).
Use datetime.now() instead of datetime.today() so that subtracting a timedelta can take the timezone (and hence daylight savings time changeovers) into account.
So then you get this:
from datetime import datetime, timedelta
def passed_midnight(delta=1):
time_now = datetime.now()
time_ago = time_now - timedelta(minutes=delta)
return time_now.date() != time_ago.date()
You probably misunderstood how to declare a function and how to call it.
Here is a version that fixed the issues with function calls:
from datetime import datetime, timedelta
def passed_midnight(delta=1):
today = datetime.today()
time_ago = today - timedelta(minutes=delta)
return today.strftime("%Y%m%d") != time_ago.strftime("%Y%m%d")
>>> print(passed_midnight(10))
False
Be careful, this code doesn't take care of time zones. The behavior will be different from a location to another
My homework is asking me to: Define a function make_birthday_intro() that takes in two arguments: a name (string), and a birth date (date).
You should utilize your make_introduction() function from Part 1! You may need to calculate a variable to pass into that function call.
Hint: use the relativedelta() function to calculate the person's current age, as well as when they will turn 1 year older. You can get the number of days or years from a relativedelta value (e.g., time_difference) by accessing the .days or .years properties (e.g., time_difference.years).
And the second part
Create a variable my_bday_intro by calling your make_birthday_intro() function and passing in your name (already a variable!) and your birthdate. Print the variable after you create it.
My tutor and I really struggled to work this out together but I believe part of the problem was that we didn't work through part one of the assignment together so he didn't fully understand this part of the assignment which I realized later may be part of why we were getting so stuck, we were missing a variable. I can't figure out where to even start with the second part of the assignment because we got so stuck on the make_birthday_intro portion.
my make_introduction code from part 1 including all code leading up to it
my_name = "Kaitlyn Griffith"
print(my_name)
my_age = 24
print(my_age)
def make_introduction(my_name, my_age):
return "Hello, my name is, " + my_name + " and I'm " + str(my_age) + " years old."
My attempt at the homework problem
import datetime
def make_birth_intro(name, date_of_birth):
age = datetime.date.today() - date_of_birth
print(age)
dateThing = datetime.date(1995, 2, 10)
make_birth_intro(make_introduction, dateThing)
I'm not sure where to start with the second part of the assignment
This function should return a string of the format "Hello, my name is {NAME} and I'm {AGE} years old. In {N} days I'll be {NEW_AGE}" (replacing {NAME}, {AGE}, {N}, and {NEW_AGE} with appropriate values).
Where it should ready "Hello, my name is Kaitlyn and I'm 24 years old. In 274 days I'll be 25"
however, my current output is:
8857 days, 0:00:00
And I am honestly not sure what I should be looking for in the second part
You are very close. To get the age in years, you could take only the year parameters from the dates and subtract them to get the difference in years.
To get the days left for the birthday, you could first get the birth date in the current year and then subtract that from the current date to get the difference in days. The complication arises when the birthday has already passed but could possibly be changed with a simple increment in years.
You would roughly do it like this (haven't tested myself):
def make_birth_intro(name, date_of_birth):
today = datetime.date.today()
age = today.year - date_of_birth.year
print(age)
this_birthday = date_of_birth.replace(year = today.year)
if(this_birthday < today):
this_birthday = this_birthday.replace(year=this_birthday.year + 1)
days_left = this_birthday - today
print(days_left.days)
I didn't read to much into the whole problem statement and as razdi said you are close, I rewrote some stuff.
With this solution you just need DOB not your age.
import datetime
def make_introduction(my_name, birth_info):
"""
Handles the printing
"""
return f"Hello, my name is {my_name} and I'm {birth_info[0]} years old, in {birth_info[1]} I'll be {birth_info[0] + 1}."
def make_birth_intro(date_of_birth):
# // is a floor division to get age in years given days
today = datetime.date.today()
age = (today - date_of_birth).days // 365
next_birthday = datetime.date(today.year, date_of_birth.month, date_of_birth.day)
if next_birthday < today:
"""
If we already had a birthday this year then add a year.
"""
next_birthday = next_birthday.replace(year=today.year + 1)
days_till_level_up = (next_birthday - today).days
return age, days_till_level_up
my_name = "Kaitlyn Griffith"
DOB = datetime.date(1995, 2, 10)
output = make_introduction(my_name, make_birth_intro(DOB))
print(output)
Output:
Hello, my name is Kaitlyn Griffith and I'm 24 years old, in 274 I'll be 25.
I'm trying to set a variable to one I have in a library. Is there a command to do this?
I'm trying to make a simple time zone converter and I want to check the input variable, but I can only check the variables in the list from pytz so I want to 'autocomplete' the variable. can I do this?
import time
import pytz
country = input("enter country")
from datetime import datetime
from pytz import timezone
fmt = "%H:%M %p"
now_utc = datetime.now(timezone('UTC'))
print (now_utc.strftime(fmt))
from pytz import all_timezones
if country in all_timezones:
country = #completed country in list 'all_timezones'
timecountry = now_utc.astimezone(timezone(country))
print (timecountry.strftime(fmt))
So what you are looking for is a way to match the user input to the strings in all_timezones and look for a valid timezone.
As far as I know, there is no built-in function that does it, you have to do it by yourself.
It's not an immediate task, as you may have multiple options (let say the user inputs just 'Europe') and you have to take this in consideration
A possible way to do is the following:
import datetime
import time
import pytz
country = input("Contry name: ")
now_utc = datetime.datetime.now(pytz.timezone('UTC'))
fmt = "%H:%M %p"
while True:
possible_countries = [ac for ac in pytz.all_timezones if country in ac]
if len(possible_countries) == 1:
cc = possible_countries[0]
timecountry = now_utc.astimezone(pytz.timezone(cc))
print(timecountry.strftime(fmt))
break
elif len(possible_countries) > 1:
print("Multiple countries are possible, please rewrite the country name")
for cs in possible_countries:
print(cs)
country = input("Contry name: ")
else:
print("No idea of the country, here are the possible choices")
for cs in pytz.all_timezones:
print(cs)
country = input("Contry name: ")
With a list comprehension I look for all the strings in all_timezones which contains the user input. If there is just one, the script assumes that is the correct one and perform the task. Otherwise if there are multiple possibilites it prints them (one per row with the for loop, but you may just print the list so its shorter on the screen) and then asks the user to rewrite the country name. If there is no match, it just print all the possibilites. You may find it ugly to see on the command line, but you should get the idea and then improve it.
If you wish to check also for spelling errors in the user input... that is a lot more difficult.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am making an alarm clock program that will have to sleep (Not make noise) until 6:00AM. The problem I am having is that I cannot get the program to wait X seconds
Pseudo Code:
X = 6:00AM - CurrentTime
time.sleep(X)
Here is my code so far:
#Imports
import datetime
import time
import pygame
WORDS = ["Wake", "Me", "Tommorow"]
#Make J.A.R.V.I.S. Listen
mic.activeListen():
#Determine time and difference of time
x = datetime.datetime.now()
x = x.total_seconds
print(x)
x = datetime.timedelta()
x = float(x) #time.sleep() Requires a float value.
time.sleep(x) #Sleeps until 6:00 AM
pygame.mixer.init()
pygame.mixer.music.load("alarm.mp3")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:
In order to create a datetime object representing 6:00am, you'd need to specify the date. E.g. if you want 6:00am today (assuming it happens in the future):
from datetime import datetime, date, time, timedelta
import time
d = date.today()
target_dt = datetime.combine(d, time(6,0))
td = target_dt - datetime.now()
time.sleep(td.total_seconds())
If you want 6am tomorrow, do:
d = date.today() + timedelta(days=1)
# the rest is the same...
You should not trust time.sleep() to stop waiting at the expected time, as any caught signal will terminate it (see answers to Upper limit in Python time.sleep()?).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I need a regex for date format in python
I want "March 29"
but not "March 29" in "March 29, YYYY", where YYYY is not 2012
Thanks,
Cheng
You don't need to use regexp.
import datetime
dt = datetime.datetime.now()
print dt.strftime('%B %d')
The result will be:
June 18
BTW, if you want to sort the list of dates and to show year only of those, which are the 2012's, than try to use split():
line = "March 29, YYYY"
if int(line.split(',')[1]) = 2012
print line
else
pass
Sounds like this:
re.compile(r'''^
(january|february|march|...etc.)
\s
\d{1,2}
\s
(,\s2012)?
$''', re.I)
Your question is not 100% clear, but it looks like you're trying to parse a date from an incoming string. If so, use the datetime module rather than a regex. It is more likely to handle locales etc. The datetime.datetime.strptime() method is designed to read dates from strings, so try something like the following:
import datetime
def myDate(raw):
# Try to match a date with a year.
try:
dt = datetime.datetime.strptime(raw, '%B %d, %Y')
# Make sure its the year we want.
if dt.year != 2012:
return None
# Error, try to match without a year.
except ValueError:
try:
dt = datetime.datetime.strptime(raw, '%B %d')
except ValueError:
return None
# Add in the year information - by default it says 1900 since
# there was no year details in the string.
dt = dt.replace(year=2012)
# Strip away the time information and return just the date information.
return dt.date()
The strptime() method returns a datetime object i.e., date and time information. Hence the last line calls the date() method to return just the date. Also note that the function returns None when there is no valid input - you can easily change this to do whatever you situation requires. See the documentation of the strptime() method for details of what the different format codes.
A few examples of its use:
>>> myDate('March 29, 2012')
datetime.date(2012, 3, 29)
>>> myDate('March 29, 2011')
>>> myDate('March 29, 2011') is None
True
>>> myDate('March 29')
datetime.date(2012, 3, 29)
>>> myDate('March 39')
>>> myDate('March 39') is None
True
You'll notice this catches and refuses to accept illegal dates (e.g., March 39) which can be tricky to handle with a regex.
The raw regex to get the month and day is: (january|february|...) \d\d?(?!\s*,\s*\d{4}).
(?!\s*,\s*\d{4}) looks ahead and makes sure the string is not followed by , YYYY. I hope I understood this part of your question. It will not match march 29, 2012 because march 29 is followed by comma space year.
I figured it out by myself
(?!\s*,\s*(1\d\d\d|200\d|2010|2011))