Syntax Error <expression Line 1> - python-3.x

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'

Related

Date formatting issue in python

import time
import sys
import json as json
import spacy
from datetime import datetime
from dateutil.parser import parse
def format_source_date(date):
if date != None:
try:
try:
dt = parse(date)
date_formatted=dt.strftime('%m/%d/%Y')
print(date_formatted)
except:
print(date)
except ValueError:
print(date)
def has_seperator(text):
if ',' in text or '/' in text or '-' in text:
print(text)
return True
else:
return False
date = 'Sep 25,2017'
has_seperator(date)
format_source_date(date)
The required answer is 09/25/2017. Instead taking current year 2021 . Is there any solution to solve this issue
Seems your date string is not a valid format,
See the following
>>> parse('Sep 25,2017')
datetime.datetime(2021, 9, 25, 0, 0)
>>> parse('Sep 25 2017')
datetime.datetime(2017, 9, 25, 0, 0)
so already have a has_seperator function, use it remove the character or use a supported format

How to make a datetime object from user input?

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())

UTC time in python with datetime

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)

How to get the date in the form of month(string) day(int) year(int)?

I was wondering how to get the date in the form of month(string) day(int) year(int) using only python?
You can use dparser to get something similar:
import dateutil.parser as dparser
from datetime import datetime, date
today = date.today()
print(datetime.date(dparser.parse(str(today),fuzzy=True)).strftime("%B, %d, %Y"))
OUTPUT:
April, 24, 2020

How do I loop through days in months in python3?

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)

Resources