I'm pretty new to python and I'm currently trying to write a code for a small project. My problem is that when I execute my code I get the date + time and I'm only interested in the date. I've tried googling the problem but haven't found a solution for using datetime and ephem together (I have to use ep.date(datetime(year, month, day)) so I can use the input date with other dates that I get from ephem).
This is a small example code of what I'm doing:
from datetime import datetime
import ephem as ep #explanation
input_date =input("Please enter the date you you'd like to know the moon phase for in the YYYY-MM-DD format: " )
year, month, day = map(int, input_date.split('-'))
datetime(int(year), int(month), int(day))
new_date = ep.date(datetime(year, month, day))
print(new_date)
And this is my output:
https://i.stack.imgur.com/0VJQM.png
If you click on the link you'll see that I get 2020/2/2 00:00:00 for the input 2020-2-2, it doesn't make my code stop working, but because I'll display this date quite often, I'd like to remove the time and only have the date.
If you just need to display the date and don't need further calculations, you can convert the ephem Date type back into a Python datetime type, then convert the Python datetime into a date.
from datetime import datetime
import ephem as ep #explanation
input_date =input("Please enter the date you you'd like to know the moon phase for in the YYYY-MM-DD format: " )
year, month, day = map(int, input_date.split('-'))
ephem_date = ep.date(datetime(year, month, day))
python_date_only = new_date.datetime().date()
print(python_date_only)
You can use ‘from datetime import date’ instead of ‘datetime’
Related
How do I convert a number to its correlating day of the week?
For example:
def string(hour_of_day, day_of_week, date) :
print(f'{day_of_week} {date} at hour {hour_of_day}')
how can I re-write the 'day_of_week' part in print so that when I use the function:
string(12, 1, '2020/02/18')
How can I get Tuesday 2020/02/18 at hour 12 instead of 1 2020/02/18 at hour 12?
Use a dictionary along the lines of
daysdict = { 1: 'Monday', 2: 'Tuesday'} exetended for all the days
then access using daysdict[1]
Although your day 1 seems to be Tuesday!
It is possible to get the day directly from the date itself - something for you to check out.
Use calendar module
If you have already the weekday number, do:
import calendar
day_of_week = 1
calendar.day_name[day_of_week]
## 'Tuesday'
The calendar module is always available in Python (it is belongs to the inbuilt standard modules).
So the dictionary {0: "Monday", 1: "Tuesday", ...} is already defined as calendar.day_name. So no need to define it yourself. Instead type import calendar and you have it available.
Use datetime module to get weekday directly from the date
from datetime import datetime
def date2weekday(date):
return datetime.strptime(date, "%Y/%m/%d").strftime('%A')
def myfunction(hour_of_day, date):
return f"{date2weekday(date)} {date} at hour {hour_of_day}"
myfunction(12, '2020/02/18')
## 'Tuesday 2020/02/18 at hour 12'
You can use the strftime method from a datetime object:
import datetime
print(datetime.datetime(2022, 10, 21).strftime('%A %Y/%m/%d'))
It will give you this answer:
Friday 2022/10/21
To adapt it to your solution just do this:
from datetime import datetime
def string(hour_of_day, date):
print(f'{date.strftime('%A %Y/%m/%d')} at hour {hour_of_day}')
string(12, datetime(year=2022, month=10, day=21))
The good thing about this solution is that you don't need to know the day of the week of a date, Python already knows that, just ask him ;)
To know more about date formatting you can visit the datetime documentation in the official Python site
Hi I have a startDate and endDate in python, the goal here is to get the same day but previous month and if the endDate does not exist returns back last date of the month.
From this
startDate = '01-03-2022'
endDate= '31-03-2022'
to
prevStartDate ='01-02-2022'
prevEndDate = '28-02-2022'
where
from datetime import datetime
from dateutil.relativedelta import relativedelta
period = endDate-startDate
prevStartDate = startDate- relativedelta(months=1)
prevEndDate = endDate+ period
how to do eosmonth like in excel so that i can put the if condition for prevEndDate the last month? or if there's another way to approach this?
I have a combination date/time string 20180104 06:09:36.234 from which I want to find the weekday in python, expecting to get the result for for the date (which is 04 January 2018) as "4" (ie Thursday) . Have searched far and wide to no avail.Can anyone help please?
Thanks CJ
See explanation of datetime.strptime
from datetime import datetime
date_string = '20180104 06:09:36.234'
date = datetime.strptime(date_string, '%Y%m%d %H:%M:%S.%f')
print(date.isoweekday()) # 4
Finally worked it out by various combinations of functions:
Identify year, month, date,
Convert to integer,
Use datetime module.
import datetime
DateTime = '20180104 06:09:36.234'
Weekday = datetime.date(int(DateTime[0:4]), int(DateTime[5:6]),
int(DateTime[7:8])).weekday()
print("Weekday = " , Weekday)
Weekday = 3
Is there a better way??
How to get the current date with zero hours in python?
When i am trying datetime.datetime.now() it is showing current date & time but i would like to get current date with zero hours.
You can use strftime to format the time as follows, this will give you the 'time' without the hours, minutes etc:
timeFormat = "%Y-%m-%d"
time_now = time.strftime(time.time())
Alternatively, if you want todays date, without a time aspect, use this from datetime
from datetime import date
today = date.today().strftime("%Y-%m-%d_%H:%M")
You can try the following code if you don't want to show hours in your code:
print str(datetime.datetime.now().date()) + " "+str(datetime.datetime.now().minute) + ":" + str(datetime.datetime.now().second)
I would like to write a function that takes a date entered by the user, stores it with the shelve function and prints the date thirty days later when called.
I'm trying to start with something simple like:
import datetime
def getdate():
date1 = input(datetime.date)
return date1
getdate()
print(date1)
This obviously doesn't work.
I've used the answers to the above question and now have that section of my program working! Thanks!
Now for the next part:
I'm trying to write a simple program that takes the date the way you instructed me to get it and adds 30 days.
import datetime
from datetime import timedelta
d = datetime.date(2013, 1, 1)
print(d)
year, month, day = map(int, d.split('-'))
d = datetime.date(year, month, day)
d = dplanted.strftime('%m/%d/%Y')
d = datetime.date(d)+timedelta(days=30)
print(d)
This gives me an error:
year, month, day = map(int, d.split('-'))
AttributeError: 'datetime.date' object has no attribute 'split'
Ultimately what I want is have 01/01/2013 + 30 days and print 01/30/2013.
Thanks in advance!
The input() method can only take text from the terminal. You'll thus have to figure out a way to parse that text and turn it into a date.
You could go about that in two different ways:
Ask the user to enter the 3 parts of a date separately, so call input() three times, turn the results into integers, and build a date:
year = int(input('Enter a year'))
month = int(input('Enter a month'))
day = int(input('Enter a day'))
date1 = datetime.date(year, month, day)
Ask the user to enter the date in a specific format, then turn that format into the three numbers for year, month and day:
date_entry = input('Enter a date in YYYY-MM-DD format')
year, month, day = map(int, date_entry.split('-'))
date1 = datetime.date(year, month, day)
Both these approaches are examples; no error handling has been included for example, you'll need to read up on Python exception handling to figure that out for yourself. :-)
Thanks. I have been trying to figure out how to add info to datetime.datetime(xxx) and this explains it nicely. It's as follows
datetime.datetime(year,month, day, hour, minute, second) with parameters all integer. It works!
Use the dateutils module
from dateutil import parser
date = parser.parse(input("Enter date: "))
you can also use
import datetime
time_str = input("enter time in this format yyyy-mm-dd")
time=datetime.datetime.strptime(time_str, "%Y-%m-%d")
datetime.datetime.strptime() strips the given string in the format you give it.
Check the library as
import datetime
and follow syntax
date = datetime.datetime(2013, 1, 1)