I am working on a project , where I have dictionary with column date called "starttime" .. I need to extract month , hour and year , day of the week.
I am stuck for now I have the below code .
{if city =='NYC':
datn = datum[('starttime')]
datn = dt.strptime(datn,"%m/%d/%y %H:%M:%S")
hour = dt.strftime(datn,"%H")
year = dt.strftime(datn,"%y")
elif city == 'Chicago':
datc = datum[('starttime')]
datc = dt.strptime(datc,"%m/%d/%y %H:%M")
month = dt.strftime(datc,"%m")
hour = dt.strftime(datc,"%H")
year = dt.strftime(datc,"%y")
else:
datw = datum[('start date')]
datw = dt.strftime (datw,"%m")
hour = dt.strftime(datw,"%H")
year = dt.strftime(datw,"%y")
return (month, hour, day_of_week)
}
my import statements are on the top of my code , as below:
from datetime import datetime
strptime translates to
"parse (convert) string to datetime object."
strftime translates to
"create formatted string for given time/date/datetime object according to specified format."
Why do you need strftime?
This is what a datetime object looks like: (2015, 7, 19, 22, 7, 44,
377000)
To someone who isn't quite familiar with this format, with the
exception of the year, what's written up there is not immediately
intuitive. So you probably would be better off with something like
Sun, 19 July, 2015. That's what strftime is used for. You simply need
to learn the proper formatting strings.
One Good Link over SO read about this !
strptime converts the string to a datetime object.
strftime creates a formatted string for given time/date/datetime object according to specified format by the user
you would use strftime to convert a datetime object like this: datetime (2018, 10, 20, 10, 9, 22, 120401) to a more readable format like "20-10-2018" or 20th of October 2018.
Related
I'm taking input that looks like "8-15 14:45" and trying to turn it into a datetime object (and then turn it back into a string). My issue is that it sets the year to 1900, but I need the year set to this year. How do I accomplish this?
So far I have datetime.datetime.strptime('8-15 14:45', '%m-%d %H:%M') which gives me datetime.datetime(1900, 8, 15, 14, 45) but I need datetime.datetime(2021, 8, 15, 14, 45). I'd like to not hardcode 2021 if I can help it.
Apologies if this is answered somewhere, my google-fu has failed me.
Use datetime.replace with datetime.today().year:
this_year = dt.datetime.today().year
dt.datetime.strptime('8-15 14:45', '%m-%d %H:%M').replace(year=this_year)
You can use the method now() of the datetime class and only ask for the property year of the returned datetime object:
from datetime import datetime
t = datetime.now().year
print(t)
>>> 2021
You can do this by replacing the year on the parsed date like this:
from datetime import datetime as dt
date = dt.strptime('8-15 14:45', '%m-%d %H:%M')
date = date.replace(year=dt.now().year)
i have seen some threats about this already but im not quite sure how to do mine. i have a string date (DD/MM/YY) then i need to subtract the day by 2 and i need to change it to (MM/DD/YY). For example, if i have a string of 01/04/2021, i need the final output to be 03/30/2021. i have tried using datetime.date but it seems like i cannot put a string of 01/04/2021 in it. Any helps? Here is what i got so far, but it doesn't really work i don't quite understand datetime library so its a little bit confusing, sorry in advance.
import datetime as dt
from dateutil.relativedelta import relativedelta
date_1 = '01/04/2021'
date_2 = list(date_1)
date_2[0:2], date_2[3:5] = date_2[3:5], date_2[0:2]
date_2 = ''.join(date_2) # change date_1 to MM/DD/YY
print(dt.date(int(date_2[0:4]),int(date_2[5:7]), int(date_2[8:10])) - relativedelta(days=2)) # i tried to minus the day out, but the code fails,
#Here is the error, in case it helps, ValueError: invalid literal for int() with base 10: '04/0'
You can use timedelta, strptime and strftime.
from datetime import datetime
from datetime import timedelta
d = '01/04/2021'
print((datetime.strptime(d, '%d/%m/%Y') - timedelta(days=2)).strftime('%m/%d/%y'))
#03/30/21
Explanation
datetime.strptime: This function allows you to take a string, provide the formatting and return a datetime object.
datetime.strptime(d, '%d/%m/%Y')
datetime.datetime(2021, 4, 1, 0, 0)
datetime.timedelta: Allows us to add and subtract time on a datetime object.
datetime.strptime(d, '%d/%m/%Y') - timedelta(days=2)
datetime.datetime(2021, 3, 30, 0, 0)
datetime.strftime: Allows us to format our datetime object as a string in the format we specify
datetime(2021, 3, 30, 0, 0).strftime('%m/%d/%y')
'03/30/21'
Joining these all together, we can convert your string to a date, make the change to the date that we want, and then convert it back to a string.
I know there are similar questions out there, but most simply convert the alphanumerical date string to a datetime object with the strptime method, which is not what I'm going for. All I'm trying to do is convert string like so.
Format of Possible Input
December 7, 2015
October 24, 2018
Desired Output
2015-12-07
2018-10-24
How I've Gone About It
""" funding_expiration[0] is equal to strings like 'December 7, 2015' """
funding_expiration = funding_expiration[0].text.split()
""" still need to convert Month (%B) to ## (%m) """
funding_expiration[1] = funding_expiration[1].replace(',', '')
# add padding to single digit days
if len(funding_expiration[1]) is 1:
funding_expiration[1] = funding_expiration[1].zfill(1)
# format numerical date string
funding_expiration = funding_expiration[2] + '-' + funding_expiration[0] + '-' + funding_expiration[1]
I'm still trying to figure out an efficient way to convert the full name of months into their corresponding numerals. I'm new to Python, so I'm wondering whether or not there's a more efficient way to accomplish this?
datetime.strptime can work in your case too. You can use the %B directive to parse full month names.
import datetime
s = 'December 7, 2015'
date_string = str(datetime.datetime.strptime(s, '%B %d, %Y').date())
>>> date_string
'2015-12-07'
Here's a solution using 3rd party dateutil:
from dateutil import parser
L = ['December 7, 2015', 'October 24, 2018']
res_str = [parser.parse(x).strftime('%Y-%m-%d') for x in L]
['2015-12-07', '2018-10-24']
I have dates in the form 26/11/2015. How can I convert them into the format 26-Nov-2015 and still keep them as dates and not strings?
Your question does not make much sense. If you keep them as dates, they have no format. The format is only manifested when you convert them to strings.
So the answer is: Store the dates as date (or datetime) objects, and use datetime.strftime with some specific format whenever you need them as a string:
>>> from datetime import date
>>> d = date(2016, 11, 26)
>>> d.strftime("%Y/%m/%d")
'2016/11/26'
>>> d.strftime("%d-%b-%Y")
'26-Nov-2016'
Conversely, use strptime to parse strings in different formats to dates:
>>> datetime.datetime.strptime("26-Nov-2015", "%d-%b-%Y")
datetime.datetime(2015, 11, 26, 0, 0)
from datetime import datetime
date = datetime.strptime('26/11/2015', '%d/%m/%Y')
print date.strftime("%d-%B-%Y")
In the above example, we are taking your input string 'dd/mm/yyyy' and turning it into a python datetime saving it to a variable called date (for future usage as per your request), and then printing it out in the format requested.
You want to use the datetime module I think. For example:
from datetime import date
a = date(2015, 11, 26)
a.strftime("%A %d of %B, %Y")
should give you 'Thursday 26 of November, 2015'
Or for your specific formatting request:
a.strftime("%d-%b-%Y") #'26-Nov-2015'
Hope this helps, good luck!
For a project I need to parse a few date strings. One date is given, which is the Monday of the week, for example: Feb 16, 2015.
Then, I have managed to extract a list of dates which looks like this:
['Wednesday', '11:00AM', '7:00PM']
['Friday', '10:15AM', '4:30PM']
['Sunday', '12:00AM', '5:00PM']
Where the first value is obviously the day, the second value is the starting time and the last value is the ending time (it's for events).
I would like to convert this to actual python datetime objects, but it must align with the starting date.
What I have tried so far is using this:
# Beginning of week
BoW = datetime.strptime('Feb 16, 2015', "%b %d, %Y")
# List of days
for day in days:
# Find the Day of the Week
# This outputs a number, 0 = Monday, 6 = Sunday
DoW = table.index(tr)
schedule.append({
'start' : BoW + timedelta(days=DoW),
'end' : BoW + timedelta(days=DoW)
})
As you can see, this will only successfully set the date, but not the hour/minute. Is there a way to easily achieve this?
You can parse out the time with strptime() as well:
timevalue = datetime.strptime(timecomponent, '%I:%M%p').time()
%I is a 12-hour clock hour value (so between 1 and 12) and %p is the AM or PM qualifier.
You can then use datetime.datetime.combine() to combine that time component with your date:
BoW = datetime.strptime('Feb 16, 2015', "%b %d, %Y").date()
start = datetime.strptime(start_time, '%I:%M%p').time()
end = datetime.strptime(end_time, '%I:%M%p').time()
start, end = datetime.combine(BoW, start), datetime.combine(BoW, end)
Demo:
>>> from datetime import datetime, timedelta
>>> BoW = datetime.strptime('Feb 16, 2015', "%b %d, %Y").date()
>>> datetime.strptime('11:00AM', '%I:%M%p').time()
datetime.time(11, 0)
>>> datetime.combine(BoW, _)
datetime.datetime(2015, 2, 16, 11, 0)
Not sure exactly what type of situation you are in, but you might try the cool NLP time parsing library parsedatetime. It would let you do something like this:
import parsedatetime
cal = parsedatetime.Calendar()
WoY_timetuple, status = cal.parse("Feb 16, 2015")
DoW_timetuple, status = cal.parse("Wednesday", sourceTime=WoY_timetuple)
start, status = cal.parseDT("11:00AM", sourceTime=DoW_timetuple)
end, status = cal.parseDT("7:00PM", sourceTime=DoW_timetuple)
So you can easily set the parsing context to get each time of day string into a full datetime object. You would need to make sure you carefully handle the status codes returned by the .parse method. If your input data has some variability in date formatting this approach could save time, otherwise Martijn's approach is probably a lot safer.