User input of standard time converted into Julian Time - python

I'm stuck on how to get a users input of year, month, day and hour converted into Julian time.
This works if I code in the time like this:
from __future__ import print_function, division
from PyAstronomy import pyasl
import datetime
# Convert calendar date to JD
dt = datetime.datetime(2017, 5, 23, 10)
print("Input date: ", dt)
print("Corresponding Julian date: ", pyasl.jdcnv(dt))
print("Corresponding reduced Julian date: ", pyasl.juldate(dt))
print()
but when I try a users input like this
from __future__ import print_function, division
from PyAstronomy import pyasl
import datetime
# Convert calendar date to JD
year = int(input('Enter a year'))
month = int(input('Enter a month'))
day = int(input('Enter a day'))
hour = int(input('Enter hour'))
dt = datetime.date(year, month, day, hour)
print("Input date: ", dt)
print("Corresponding Julian date: ", pyasl.jdcnv(dt))
print("Corresponding reduced Julian date: ", pyasl.juldate(dt))
print()
I get the error
TypeError Traceback (most recent call
last)
<ipython-input-4-2b1701814572> in <module>()
11 day = int(input('Enter a day'))
12 hour = int(input('Enter hour'))
---> 13 dt = datetime.date(year, month, day, hour)
14 print("Input date: ", dt)
15 print("Corresponding Julian date: ", pyasl.jdcnv(dt))
TypeError: function takes at most 3 arguments (4 given)

You write the wrong code in line in your second example:
dt = datetime.date(year, month, day, hour)
The correct is:
dt = datetime.datetime(year, month, day, hour)

Related

Trying to make a countdown, where you input the the date

Trying to make a countdown, where you input the date:
from datetime import datetime
year = int(input('Enter a year: '))
month = int(input('Enter a month: '))
day = int(input('Enter a day: '))
date = datetime.date(year, month, day)
countdown = date - datetime.now()
print(countdown)
The error is:
line 7, in <module>
date = datetime.date(year, month, day)
TypeError: descriptor 'date' for 'datetime.datetime' objects doesn't apply to a 'int' object
Try this:
date = datetime(year, month, day).date()
countdown = date - datetime.now().date()
print(countdown)
That error is raised when an operation or function is applied to an object of inappropriate type.
A datetime object is a single object containing all the information from a date object and a time object.
A date object represents a date (year, month and day) in an idealized calendar, the current Gregorian calendar indefinitely extended in both directions.
Try adding .date() to datetime object.
e.g.: datetime(year, month, day).date()

How to handle date error with months in datetime.replace in python?

I have the date object which is as follows. Date: 2025-11-30. If I add 3 month to it using following code, it will raise an Exception as follows.
code:
def get_next_n_month_forward(date, n):
if date.month + n > 12:
next_month = date.replace(year=date.year + 1,
month=(date.month + n) % 12)
else:
next_month = date.replace(month=(date.month + n))
return next_month
exception:
ValueError: day is out of range for month
As far as I can understand from error it is because february does not have 30th day.
Question: How can I make it set to the last day of the month? !Note: In my case it would be 29th or 28th of February.
You can use timedelta object to increase and decrease dates
from datetime import timedelta
import datetime
d = datetime.datetime.today()
new_d = d + timedelta(days=1)
In order to set the date to the last day of month, you can set the date to the 1st of the next month and then decrease it by 1 day:
from datetime import timedelta
import datetime
day = datetime.datetime.today()
prev_month_last_day = day.replace(day=1) - timedelta(days=1)

Displaying age in seconds using Python3

I want to replicate the trick Paul Erdoes used to pull as a child:
Tell someone how many seconds he is old, based on his date of birth and the current time.
This is what the current code looks like:
# For displaying age in seconds
from datetime import datetime
year = int(input("year: "))
month = int(input("month: "))
day = int(input("day: "))
# This is resulting in datetime.timedelta object with attr days, seconds, microseconds
#delta = datetime.now() - datetime(year, month, day)
print("You are " + str(datetime.now() - datetime(year, month, day)) + " seconds old.")
#str(delta.seconds)
Result is something around 770xx seconds, but that is incorrect, as each day is already 36000 * 24 seconds.
So how do I use the datetime library to perform what I want to do?
You can use total_seconds to calculate the difference in seconds between two dates
from datetime import datetime
year = int(input("year: "))
month = int(input("month: "))
day = int(input("day: "))
#Calculate time in seconds between now and the day of birth
time_in_seconds = (datetime.now() - datetime(year=year, month=month, day=day)).total_seconds()
print("You are {} seconds old.".format(time_in_seconds))
The output will be
year: 1991
month: 1
day: 31
You are 892979995.504128 seconds old.

Get month by week, day and year

I want to know how you get the months by the giving day, week number and year.
For example if you have something like this
def getmonth(day, week, year):
# by day, week and year calculate the month
print (month)
getmonth(28, 52, 2014)
# print 12
getmonth(13, 42, 2014)
# print 10
getmonth(6, 2, 2015)
# print 1
Per interjay's suggestion:
import datetime as DT
def getmonth(day, week, year):
for month in range(1, 13):
try:
date = DT.datetime(year, month, day)
except ValueError:
continue
iso_year, iso_weeknum, iso_weekday = date.isocalendar()
if iso_weeknum == week:
return date.month
print(getmonth(28, 52, 2014))
# 12
print(getmonth(13, 42, 2014))
# 10
print(getmonth(6, 2, 2015))
# 1
You can do it with the isoweek module, something like this for your first example:
from isoweek import Week
w = Week(2014, 52)
candidates = [date for date in w.days() if date.day == 28]
assert len(candidates) == 1
date = candidates[0] # your answer
I'm using python-dateutil when I need to implement some tricky date operations.
from datetime import date
from dateutil.rrule import YEARLY, rrule
def get_month(day, week, year):
rule = rrule(YEARLY, byweekno=week, bymonthday=day, dtstart=date(year, 1, 1))
return rule[0].month
from datetime import datetime, timedelta
def getmonth(day, week, year):
d = datetime.strptime('%s %s 1' % (week-1, year), '%W %Y %w')
for i in range(0, 7):
d2 = d + timedelta(days=i)
if d2.day == day:
return d2.month

Get a datetime format from a string in Python

Hello sorry for the ambiguous title, here's what I want to do :
I have a string:
month = '1406'
that corresponds to the month of June, 2014.
How can I dynamically say that that string represents the month of June and I specifically want the last day of the month.
So I want to write it in the format: '%Y-%m-%d %H:%M:%S' and have:
'2014-06-30 00:00:00'
You get the last day of a given month with the calendar.monthrange() function. Turn your string into two integers (month, year), create a datetime object from the year, month and last day of the month:
from datetime import datetime
from calendar import monthrange
year, month = int(month[:2]), int(month[2:])
year += 2000 # assume this century
day = monthrange(year, month)[1]
dt = datetime(year, month, day) # time defaults to 00:00:00
Demo:
>>> from datetime import datetime
>>> from calendar import monthrange
>>> month = '1406'
>>> year, month = int(month[:2]), int(month[2:])
>>> year += 2000 # assume this century
>>> day = monthrange(year, month)[1]
>>> datetime(year, month, day)
datetime.datetime(2014, 6, 30, 0, 0)
>>> print datetime(year, month, day)
2014-06-30 00:00:00
The default string conversion for datetime objects fits your desired format already; you can make it explicit by calling str() on it or by using the datetime.datetime.isoformat() method, as you see fit.
This seems to do the trick:
import datetime
mon = '1406'
y, m = divmod(int(mon), 100)
dt = datetime.datetime(2000 + y + m // 12, m % 12 + 1, 1) - datetime.timedelta(days=1)
print dt

Categories

Resources