How can I use datetime.utcnow() and datetime.date.today() together? In case I am running code A it throws error and Code B other one. I want to use both of these in my code.
A
from datetime import datetime, timedelta
path = datetime.utcnow().strftime(f'{category}/%Y%m%d/%H:%M')
for year in range(2014, 2018):
for month in range(start_month_number, 13):
this_month = datetime.date.today().replace(year=year, month=month, day=1)
print(this_month)
error - AttributeError: 'method_descriptor' object has no attribute 'today'
B
import datetime
path = datetime.utcnow().strftime(f'{category}/%Y%m%d/%H:%M')
for year in range(2014, 2018):
for month in range(start_month_number, 13):
this_month = datetime.date.today().replace(year=year, month=month, day=1)
print(this_month)
error- AttributeError: module 'datetime' has no attribute 'utcnow'
Code B run fine in case there is no line -->curryear = datetime.utcnow().strftime('%Y')
Either import the module that you need, or the classes you need from the module - not both. Then, write your code according to what you have imported:
A:
from datetime import datetime, date
path = datetime.utcnow().strftime(f'{category}/%Y%m%d/%H:%M')
for year in range(2014, 2018):
for month in range(1, 13):
this_month = date(year=year, month=month, day=1)
print(this_month)
or B:
import datetime
path = datetime.datetime.utcnow().strftime(f'{category}/%Y%m%d/%H:%M')
for year in range(2014, 2018):
for month in range(1, 13):
this_month = datetime.date(year=year, month=month, day=1)
print(this_month)
Related
I am trying to make an alarm clock. How to make a datetime object from user-input, where the user-input is hours, minutes, and secs seperately. For example:
from datetime import datetime
# user-input: at 2:30
hr = "2"
m = "30"
s = "0"
from datetime import datetime
def GetDate():
isValid=False
while not isValid:
userIn = input("Type Date dd/mm/yy: ")
try: # strptime throws an exception if the input doesn't match the pattern
d = datetime.datetime.strptime(userIn, "%d/%m/%y")
isValid=True
except:
print("Invalid")
return d
#test the function
print(GetDate())
from datetime import datetime, timedelta
hours = input("Number of hours:")
time = datetime.now() + timedelta(hours=hours)
print(time)
_________________________________________________________________
Traceback (most recent call last):
File "C:/Users/uruma/Desktop/test.py", line 4, in <module>
time = datetime.now() + timedelta(hours=hour)
TypeError: unsupported type for timedelta hours component: str
from datetime import datetime, timedelta
hours = 4
time = datetime.now() + timedelta(hours=hours)
print(time)
____________________________
2020-10-28 06:00:30.149767
What I'm trying to do here is ask the user for the number of hours in order to calculate what hour will be after a certain amount of time, but I get an error. But if instead of the "input" code you put a number ... How to solve?
By default, the value from input() is string.
Convert the input string into int
from datetime import datetime, timedelta
hours = int(input("Number of hours:"))
time = datetime.now() + timedelta(hours=hours)
print(time)
You need to convert the user input to an integer before using it. Python input is a string by default.
hours = int(input('Enter the number of hours: '))
Say for the year of 2020, how do I iterate through the days in the months so that my outcome would be in the following format:
Jan1
Jan2
Jan3
....
Jan31
Feb1
I've tried so many things online but I couldnt find an answer. Please help :(
Both of these methods will handle leap years correctly out of the box.
Using a simple while loop:
from datetime import datetime, timedelta
def iter_days(year):
dt = datetime(year, 1, 1)
while dt.year == year:
yield dt
dt += timedelta(days=1)
Using date rules:
from datetime import datetime
from dateutil.rrule import rrule, DAILY
def iter_days(year):
first_date = datetime(year, 1, 1)
last_date = datetime(year, 12, 31)
return rrule(DAILY, dtstart=first_date, until=last_date)
Both would be used the same:
for dt in iter_days(2020):
print(dt.strftime('%b%-d'))
The format string '%b%-d' will give you the format you specified in your question. I don't know if that was a requirement or not.
This is crude but gets what you want for 2020. You'll need to change 366 to 365 for non-leap-years.
#!/usr/bin/python3
import datetime
startDate = '2020-01-01'
start = datetime.datetime.strptime(startDate, '%Y-%m-%d')
for dayNum in range(0,366):
dayOfYear = start + datetime.timedelta(days=dayNum)
print(dayOfYear.strftime('%b %d, %Y'))
The calendar module offers quite a bit of functionality.
Here is a solution that works for any given year
import calendar as cal
for mi in range(1,13):
_, days = cal.monthrange(2020, mi)
for d in range(1, days+1):
print(cal.month_name[mi], d)
I have two tables:
-event dates
-return dates
Some event dates are not at a trading day.
How can I change the event date to the next trading day?
So if event date is not in return dates, take the next day in return dates.
The approach to change weekend days to working days does not work because of days like Christmas.
The best would be to look up the next day in the return table.
for i in event['date']:
if i is not in return ['date'].values:
event ['date']=i+datetime.timedelta(days=1)
but this doenst work
I am working with dataframes and dates have the format datetime64[ns]. If the event date does not exist in return date than event date plus one day
Edit
After the clarifications concerning the desired logic, here is the new solution
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
# Create two df
event_date = datetime.now()
event_dates = pd.DataFrame([datetime(2020, 2, _) for _ in range(1, 29)], columns=['date'])
print(event_dates.date[0])
# 2020-02-01 00:00:00
return_dates = pd.DataFrame([datetime(2020, 1, _) for _ in range(1, 32)], columns=['date'])
# Apply logic
event_dates.date = [_ if _ in return_dates.date else _ + timedelta(days=1) for _ in event_dates.date]
print(event_dates.date[0])
# 2020-02-02 00:00:00
Base Python
Here is a solution using the standard datetime library
from datetime import datetime
from typing import List
def get_next_trade_date(date: datetime, date_list: List[datetime]) -> datetime: # The annotations here are just to specify the types of the objects
if date in date_list: # Check if the date is contained in the list
return date
delta, res = None, None # Initialize both to None
for _ in date_list:
tmp = abs((date - _).days) # Time difference in current iteration
if not delta or tmp < delta: # See bullet point 1.
delta, res = tmp, _
return res
if __name__ == '__main__':
event_date = datetime.now()
return_dates = [datetime(2020, 1, _) for _ in range(1, 32)]
print(get_next_trade_date(event_date, return_dates))
# 2020-01-01 00:00:00
Notice that
The condition not delta or tmp < delta is twofold: in the first iteration delta, res are both None so we will overwrite them with tmp, _. We catch this by using not delta. The other part (tmp < delta) is more obvious: if we have a new minimal delta then we overwrite delta, res.
I only considered days intervals ((date - _).days), you could go further into details (see datetime.timedelta for more info)
coming from R I believe there must be a simpler solution using numpy - see below
Numpy
This solution uses numpy. (date_list - date) is an array of timedeltas, (date_list - date).argmin() returns the index of the minimal value.
from datetime import datetime
import numpy as np
def get_next_trade_date(date: datetime, date_list: np.ndarray) -> datetime:
return date_list[(date_list - date).argmin()]
if __name__ == '__main__':
event_date = datetime.now()
return_dates = np.array([datetime(2020, 1, _) for _ in range(1, 32)])
print(get_next_trade_date(event_date, return_dates))
# 2020-01-01 00:00:00
I'm trying to convert a date in a string format (13/06/2017) into a date format June 13, 2007. I have written the code but I keep getting a syntax error for my first line which is the definition of the function line.
My code is this:
def printDate(date):
import datetime
newdate = datetime.strptime(date, %d/%m/%Y)
d = newdate.strftime(%b %d, %Y)
return d
You didn't pass the parameter "date format" as a string, that's why, also be sure to import datetime module as follows:
from datetime import datetime
def printDate(date):
newdate = datetime.strptime(date, "%d/%m/%Y")
d = newdate.strftime("%B %d, %Y")
return d
Test:
printDate("13/06/2017")
>> 'June 13, 2017'