I'm quite lost and I'm in need of trying to format some code so it ends up having dashes in the date. I can get 3, 12, 28 but I can't get 3-12-28. I am a super new beginner so I'm quite lost at the moment.
year = 3
month = 12
day = 28
print(date)
Try
print("{0}-{1}-{2}".format(year,month,day))
You could use datetime to format the result
import datetime
year = 3
month = 12
day = 28
dt = (datetime.date(year, month, day))
print(dt)
the result will be 0003-12-28
if you want more examples of datetime you could take a look at https://docs.python.org/2/library/datetime.html#
As you say you are new to python you can concatenate the strings together.
year = 3
month = 12
day = 28
date = year + "-" + month + "-" + day
print(date)
Alternatively you can use format to set the variables in your required format.
print(f"{year}-{month}-{day}")
Another method is to use datetime if you are using todays date
import datetime
today = datetime.date.today()
print(today)
Related
I need to parse strings representing 6-digit dates in the format yymmdd where yy ranges from 59 to 05 (1959 to 2005). According to the time module docs, Python's default pivot year is 1969 which won't work for me.
Is there an easy way to override the pivot year, or can you suggest some other solution? I am using Python 2.7. Thanks!
I'd use datetime and parse it out normally. Then I'd use datetime.datetime.replace on the object if it is past your ceiling date -- Adjusting it back 100 yrs.:
import datetime
dd = datetime.datetime.strptime(date,'%y%m%d')
if dd.year > 2005:
dd = dd.replace(year=dd.year-100)
Prepend the century to your date using your own pivot:
year = int(date[0:2])
if 59 <= year <= 99:
date = '19' + date
else
date = '20' + date
and then use strptime with the %Y directive instead of %y.
import datetime
date = '20-Apr-53'
dt = datetime.datetime.strptime( date, '%d-%b-%y' )
if dt.year > 2000:
dt = dt.replace( year=dt.year-100 )
^2053 ^1953
print dt.strftime( '%Y-%m-%d' )
You can also perform the following:
today=datetime.datetime.today().strftime("%m/%d/%Y")
today=today[:-4]+today[-2:]
Recently had a similar case, ended up with this basic calculation and logic:
pivotyear = 1969
century = int(str(pivotyear)[:2]) * 100
def year_2to4_digit(year):
return century + year if century + year > pivotyear else (century + 100) + year
If you are dealing with very recent dates as well as very old dates and want to use the current date as a pivot (not just the current year), try this code:
import datetime
def parse_date(date_str):
parsed = datetime.datetime.strptime(date_str,'%y%m%d')
current_date = datetime.datetime.now()
if parsed > current_date:
parsed = parsed.replace(year=parsed.year - 100)
return parsed
My Date should always fall on 8th or 22nd that comes off the input date.
For Example:
If the input date is 20190415 then the output date should be 20190422 as that's the nearest date and if input date is 20190424 then the output date should be 20190508.
Example1:
input_date = 20190415
Expected output_date = 20190422
Example2:
input_date = 20190424
Expected output_date = 20190508
Example3:
input_date = 20190506
Expected output_date = 20190508
Example4:
input_date = 20191223
Expected output_date = 20200108
How do we achieve this using Python?
You can check if the day is greater than 22, and if so you set it to the 8th of the next month. If it's between 8 and 22 you set it to 22 of the same month and if it's below the 8th you set it to the 8th of the month. There's probably more elegant ways to do it using date math, but this will work for your scenario.
Use the datetime module to find out what the "next month" is. One way to do it is to add a timedelta of 1 month to the first of the current month, and then change the date on that datetime object to the 8th. Here's a quick example of how that might look like:
from datetime import date, timedelta
input_date = date(2019, 12, 23)
if input_date.day > 22:
output_date = date(input_date.year, input_date.month) + timedelta(days=31)
output_date = output_date.replace(day = 8)
You can read a lot more about the details of how the datetime module works on the official documentation. It's kind of a long read, but I actually have that page bookmarked because I always have to go back and reference how to actually use the module :)
Considering the input as string, next date can be calculated using timedelta, check out the below code:
if 8<datetime.strptime(input_date, "%Y%m%d").day < 22:
delta = 22 - datetime.strptime(input_date, "%Y%m%d").day
print((datetime.strptime(input_date, "%Y%m%d") +
timedelta(days=delta)).strftime("%Y%m%d"))
elif datetime.strptime(str(input_date), "%Y%m%d").day < 8:
delta = 8 - datetime.strptime(input_date, "%Y%m%d").day
print((datetime.strptime(input_date, "%Y%m%d") +
timedelta(days=delta)).strftime("%Y%m%d"))
else:
delta = (datetime.strptime(input_date, "%Y%m%d")+ relativedelta(months=+1)).day -8
print((datetime.strptime(input_date, "%Y%m%d") + relativedelta(months=+1) -
timedelta(days=delta)).strftime("%Y%m%d") )
How can I print the date of the last Tuesday of each month for next year using Python.
For example the first line outputted would be: 30/Jan/2018
I do not want to have the full name of the month only the first 3 characters!
Currently I have figured out how to get the next year:
import datetime
now = datetime.datetime.now()
next_year = now.year + 1
Can anyone please help?
The calendar module is perfect for this:
You can use calendar.month_abbr which is an array of
abbreviated months just like you want.
week is an array representing the days of the week starting at Monday so Tuesday would be week[1].
import calendar
import datetime
now = datetime.datetime.now()
next_year = now.year + 1
for month in range(1, 13):
last_tuesday = max(week[1] for week in calendar.monthcalendar(next_year, month))
print('{}/{}/{}'.format(last_tuesday, calendar.month_abbr[month], next_year))
Output:
30/Jan/2018
27/Feb/2018
27/Mar/2018
24/Apr/2018
29/May/2018
26/Jun/2018
31/Jul/2018
28/Aug/2018
25/Sep/2018
30/Oct/2018
27/Nov/2018
25/Dec/2018
I would also suggest the pandas DateOffset object LastWeekOfMonth.
Describes monthly dates in last week of month like "the last Tuesday
of each month"
from pandas.tseries.offsets import LastWeekOfMonth
def last_tues(year):
return (pd.date_range('1/1/' + str(year), periods=12, freq='M')
- LastWeekOfMonth(n=1, weekday=1)).strftime('%d/%b/%Y'))
last_tues(2018)
Out[31]:
array(['30/Jan/2018', '27/Feb/2018', '27/Mar/2018', '24/Apr/2018',
'29/May/2018', '26/Jun/2018', '26/Jun/2018', '28/Aug/2018',
'25/Sep/2018', '30/Oct/2018', '27/Nov/2018', '25/Dec/2018'],
dtype='<U11')
Getting error for December month.
ValueError: month must be in 1..12
def last_day_of_month(ds):
cur_ds = datetime.strptime(ds, '%Y-%m-%d')
next_month = datetime(year=cur_ds.year, month=cur_ds.month+1, day=1)
last_day_month = next_month - timedelta(days=1)
return datetime.strftime(last_day_month, '%Y-%m-%d')
print last_day_of_month('2016-12-01')
In line 3 month=cur_ds.month+1 you are giving 13th month which is not valid. If you want to calculate last day of a given month you could also use month range from calendar library.
>>import calendar
>>year, month = 2016, 12
>>calendar.monthrange(year, month)[1]
31
You can't make a datetime with a month of 13. So you have to find a way to fix it. A simple solution is to convert the incremented month to an extra year:
# Reduce 12 to 1, 0 and all other #s to 0, #
extrayear, month = divmod(cur_ds.month, 12)
# Add 1 or 0 to existing year, add one to month (which was reduced to 0-11)
next_month = datetime(year=cur_ds.year + extrayear, month=month + 1, day=1)
You're passing in 12 as current month, then adding one to get next_month, making it 13. Check for the 12 case and set month=1 instead.
this is how I did it.
from django.utils import timezone
from calendar import monthrange
from datetime import datetime
current = timezone.now()
firstdayofmonth = current.replace(day=1)
endmonth = monthrange(current.year, current.month)
lastdayofmonth = datetime(current.year, current.month, endmonth[1])
I need help with a program.
How do I add 3 weeks (21 days) to any given date when the user can control the date?
The user will enter the date YYYY-MM-DD.
Below I'm trying to locate the hyphen and make sure there is only 2. This is what I have so far but all it does is repeat itself, can someone tell me where I went wrong ?:
date = raw_input("Enter date: ")
i = 0
while i <= len(date):
if date[i] != "-":
i = i + 1
print date
Now I'm picking out year, month, day. Is there an easier way to do this cause I need to account for the change months etc ?
year = date[0:4]
month = date[5:7]
day = date[9:11]
thanks
Use datetime module to the task. You create a datetime aware object and add 21 days timedelta object to it.
>>> import datetime
>>> u = datetime.datetime.strptime("2011-01-01","%Y-%m-%d")
>>> d = datetime.timedelta(days=21)
>>> t = u + d
>>> print(t)
2011-01-22 00:00:00
You can use a datetime.timedelta object to represent 3 weeks and then just add that to the datetime object that represents the user's input.
import datetime
date = raw_input("Enter date: ")
aDate = datetime.datetime.strptime(date,"%Y-%m-%d")
threeWeeks = datetime.timedelta(weeks = 3)
print aDate + threeWeeks
See http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior for details about using the strptime method.
Try this, I am sure its the shortest and easiest way to go
from dateutil.relativedelta import relativedelta
period = date.today() + relativedelta(weeks=+1)
you can use datetime.strptime to get input from user as date
from datetime import datetime
i = str(raw_input('date'))
try:
dt_start = datetime.strptime(i, '%Y, %m, %d')
except ValueError:
print "Incorrect format"
and then to add 3 weeks (21 days)
dt_start = dt_start + datetime.timedelta(days=21)
There you go