I scraped some dates with this format:
review_date = ['9 August 2018 ', '7 August 2018 ']
and I wanted to convert each string to a datetime format like this '%d-%m-%Y'
for d in review_date:
d = datetime.datetime.strptime(d, '%d-%m-%Y')
but the following error is appearing because it isn't in the inicial format datetime wants
ValueError: time data '9 August 2018 ' does not match format
'%d-%m-%Y'
Is there an easy way to convert this or do I need to replace my string?
strptime converts the string to a datetime() object. The format string you pass to it is to specify the format the string is already in:
d = datetime.datetime.strptime(d, '%d %B %Y') # %B is the full month name
You can generate any string you want from that object later with strftime() - then you can pass the format you want:
s = d.strftime('%d-%m-%Y')
You can chain the calls in a single line:
result = datetime.datetime.strptime(d, '%d %B %Y').strftime('%d-%m-%Y')
Related
How to convert string '17 Nov 2021' into data object "20211117"?
I've tried:
_date=datetime.strptime(_dateAsString, '%Y%m%d')
but it does not work :/
Parse to datetime object and then convert back to string with different date format as follows:
import datetime
_date = datetime.datetime.strptime("17 Nov 2021", "%d %b %Y").strftime("%Y%m%d")
# Result: '20211117'
You can review the available strftime() and strptime() format codes if it's not clear what the various codes e.g. %d and %b represent.
I work with api in python3 in this api return date like this
'Jun 29, 2018 12:44:14 AM'
but i need just hours, minute ad second like this
12:44:14
are there a fonction that can format this
It looks like the output is a string. So, you can use string slicing:
x = 'Jun 29, 2018 12:44:18 AM'
time = x[-11:-3]
It's best to use negative indexing here because the day may be single-digit or double-digit, so a solution like time = x[13:21] won't work every time.
If you're inclined, you may wish to use strptime() and strftime() to take your string, convert it into a datetime object, and then convert that into a string in HH:MM:SS format. (You may wish to consult the datetime module documentation for this approach).
Use the datetime module. Use .strptime() to convert string to datetime object and then .strftime() to convert to your required string output. Your sample datetime string is represented as '%b %d, %Y %H:%M:%S %p'
Ex:
import datetime
s = 'Jun 29, 2018 12:44:14 AM'
print( datetime.datetime.strptime(s, '%b %d, %Y %H:%M:%S %p').strftime("%H:%M:%S") )
Output:
12:44:14
I am facing trouble while converting string into dateobject in python.
I want to convert string '10 JAN 2016" to dateobject so that i can compare it to the present date and get the time difference.
I tired but i am getting formatting error.What is the solution to this problem?
Use the datetime module.
import datetime
date = datetime.datetime.strptime('10 jan 2016`,'%d %b %Y').date()
difference_in_dates = date - datetime.date.today() #this returns a timedelta object
Use datetime.timedelta objects for comparison.
You can look up the documentation about the formats (%d, %m, etc.) here
You need to use a valid format.
Try looking here: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
dt = '10 JAN 2016'
dtime = datetime.datetime.strptime(dt, "theformat")
I'm using python 3.5.
I have a string formatted as mm/dd/yyyy H:MM:SS AM/PM that I would like as a python datetime object.
Here is what I've tried.
date = "09/10/2015 6:17:09 PM"
date_obj = datetime.datetime.strptime(date, '%d/%m/%Y %I:%M:%S %p')
But this gets an error because the hour is not zero padded. The formatting was done per the table on the
datetime documentation, which does not allow the hour to have one digit.
I've tried splitting the date up, adding a zero and then reassembling the string back together, while this works, this seems less robust/ideal.
date = "09/10/2015 6:17:09 PM"
date = date.split()
date = date[0] + " 0" + date[1] + " " + date[2]
Any recommendation on how to get the datetime object directly, or a better method for padding the hour would be helpful.
Thank you.
There is nothing wrong with this code:
>>> date = "09/10/2015 6:17:09 PM"
>>> date_obj = datetime.datetime.strptime(date, '%m/%d/%Y %I:%M:%S %p')
>>> date_obj
datetime.datetime(2015, 9, 10, 18, 17, 9)
>>> print(date_obj)
2015-09-10 18:17:09
The individual attributes of the datetime object are integers, not strings, and the internal representation uses 24hr values for the hour.
Note that I have swapped the day and month in the format strings as you state that the input format is mm/dd/yyyy.
But it seems that you actually want it as a string with zero padded hour, so you can use datetime.strftime() like this:
>>> date_str = date_obj.strftime('%m/%d/%Y %I:%M:%S %p')
>>> print(date_str)
09/10/2015 06:17:09 PM
# or, if you actually want the output format as %d/%m/%Y....
>>> print(date_obj.strftime('%d/%m/%Y %I:%M:%S %p'))
10/09/2015 06:17:09 PM
I am trying to write a program that asks for the user to input the date in the format mm/dd/yyyy and convert it. So, if the user input 01/01/2009, the program should display January 01, 2009. This is my program so far. I managed to convert the month, but the other elements have a bracket around them so it displays January [01] [2009].
date=input('Enter a date(mm/dd/yyy)')
replace=date.replace('/',' ')
convert=replace.split()
day=convert[1:2]
year=convert[2:4]
for ch in convert:
if ch[:2]=='01':
print('January ',day,year )
Thank you in advance!
Don't reinvent the wheel and use a combination of strptime() and strftime() from datetime module which is a part of python standard library (docs):
>>> from datetime import datetime
>>> date_input = input('Enter a date(mm/dd/yyyy): ')
Enter a date(mm/dd/yyyy): 11/01/2013
>>> date_object = datetime.strptime(date_input, '%m/%d/%Y')
>>> print(date_object.strftime('%B %d, %Y'))
November 01, 2013
You might want to look into python's datetime library which will take care of interpreting dates for you. https://docs.python.org/2/library/datetime.html#module-datetime
from datetime import datetime
d = input('Enter a date(mm/dd/yyy)')
# now convert the string into datetime object given the pattern
d = datetime.strptime(d, "%m/%d/%Y")
# print the datetime in any format you wish.
print d.strftime("%B %d, %Y")
You can check what %m, %d and other identifiers stand for here: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
As a suggestion use dateutil, which infers the format by itself:
>>> from dateutil.parser import parse
>>> parse('01/05/2009').strftime('%B %d, %Y')
'January 05, 2009'
>>> parse('2009-JAN-5').strftime('%B %d, %Y')
'January 05, 2009'
>>> parse('2009.01.05').strftime('%B %d, %Y')
'January 05, 2009'
Split it by the slashes
convert = replace.split('/')
and then create a dictionary of the months:
months = {1:"January",etc...}
and then to display it do:
print months[convert[0]] + day + year