This question already has answers here:
Python convert date format
(3 answers)
Closed 6 months ago.
I have date in the form of YYYY-MM-DD how can i format that date into Aug 26, 2022.
def return_date():
date_returned = YYYY-MM-DD
return date_returned in form of Aug 26, 2022
here is your code:
from datetime import date
date_string = '2022-08-26'
date.fromisoformat(date_string).strftime('%b %d, %Y') # 'Aug 26, 2022'
You can easily understand with this example:
from datetime import datetime
# Get current Date
date = datetime.now()
# Represent dates in short textual format
print("dd-MMM-yyyy:", date.strftime("%b %d, %Y"))
# prints "dd-MMM-yyyy: Aug 26, 2022"
I hope this will help you.
Use strptime to decode the string then strftime to format it to your liking as follows:
from time import strptime, strftime
def return_date(ds): # data as string in the form YYYY-MM-DD
return strftime('%b %d, %Y', strptime(ds, '%Y-%m-%d'))
print(return_date('2022-08-26'))
Output:
Aug 26, 2022
Is this what you are trying to accomplish?
import datetime
def return_date(ymd_format):
year, month, day = ymd_format.split("-")
return datetime.datetime(int(year), int(month), int(day)).strftime("%b %d, %Y")
print(return_date("2022-08-26")) # prints "Aug 26, 2022"
Related
How to convert date to mysql date format like Dec 21, 2019 to 2019-12-21 in python.
Please help, I am new to python.
i tried date.strftime("%Y-%m-%d %H:%M:%S") but its won't work.
You need to provide the correct format string.
import datetime
d = datetime.datetime.strptime("Dec 21, 2019","%b %d, %Y")
d.strftime("%Y-%m-%d")
If you're not sure about the format of date and/or expecting multiple formats, you can use the below code snippet
from dateutil.parser import parse
d = parse("Dec 21, 2019")
d.strftime("%Y-%m-%d")
Example snippet for date conversion.
from datetime import datetime
oldformat = 'Dec 21, 2019'
datetimeobject = datetime.strptime(oldformat,'%b %d, %Y')
newformat = datetimeobject.strftime('%Y-%m-%d')
print(newformat)
The dates that I have in a data frame are formatted like this:
Apr 5, 2010.
How can I convert them to datetime?
Here's what I've tried so far:
date_time_str = 'Sep 28, 2019'
date_time_obj = datetime.datetime.strptime(date_time_str, '%m %d, %Y')
print(date_time_obj)
But I know this is wrong.
(I've tried looking for similar questions on here, but most people have their string dates formatted like 05-05-2010.)
The following code will produce a new datetime object with the values you would like.
from datetime import datetime
date_time_str = 'Sep 28, 2019'
date_time_obj = datetime.strptime(date_time_str, '%b %d, %Y')
print(date_time_obj)
print(type(date_time_obj)) # verify object type
I am trying to convert a string into date format in Python.
I am using following statement
datetime_obj = datetime.datetime.strptime("Sun Aug 19 16:24:31 PDT 2018", "%a %b %d %H:%M:%S %Z %Y")
However, I get an error -
ValueError: time data 'Sun Aug 19 16:24:31 PDT 2018' does not match format '%a %b %d %H:%M:%S %Z %Y'
If I remove the timezone from the date string and the format string, the code works perfect. Which leads me to believe that the issue is related to the timezone but I am not sure what actions should be taken.
I am in eastern timezone and the time zone in the string is in Pacific timezone.
Appreciate any help on this.
As mentioned in this answer you can use python-dateutil for this:
>>> from dateutil import parser
>>> datetime_obj = parser.parse("Sun Aug 19 16:24:31 PDT 2018")
datetime.datetime(2018, 8, 19, 16, 24, 31)
Standard datetime module behaves very strangely with parsing timezones, as I see reading this answer in question related to similar problem.
This question already has answers here:
Parse CEST/CET time in python
(2 answers)
Closed 5 years ago.
I am creating simple RSS reader. Storing date of last read newest entry in newest_entry_datetime and then when reading again channel I am comparing entry time to newest_entry_datetime with < symbol as I read that Python is smart enough to recognize and compare datetime.
It works on the same day when time part is changing but on the next day newest date is implemented as old.
import datetime
import locale
#locale.setlocale(locale.LC_ALL, 'English_United States.1252')
newest_entry_datetime = 'Thu, 21 Dec 2017 16:02:03 CET'
entry_published = 'Fri, 22 Dec 2017 08:19:15 CET'
#dt_newest = datetime.datetime.strptime (newest_entry_datetime, "%a, %d %b %Y %H:%M:%S %Z" )
if (entry_published <= newest_entry_datetime):
print('Entry date is older')
else:
print('Entry date is NEW')
With such code I am getting result: "Entry date is older" which is wrong.
Second idea was to convert datestamps to datetime but I am getting:
ValueError: time data 'Thu, 21 Dec 2017 16:02:03 CET' does not match format '%a, %d %b %Y %H:%M:%S %Z'
even if I will change locale to US.
No clue how to do that correctly. Could you please help?
Thanks to Anton vBR answer that CET is not recognized I just removed this part of string as feed will always have the same timezone.
Final code that works and gives proper result is here.
import datetime
import locale
locale.setlocale(locale.LC_ALL, 'English_United States.1252')
newest_entry_datetime = 'Thu, 21 Dec 2017 16:02:03 CET'
entry_published = 'Fri, 22 Dec 2017 08:19:15 CET'
newest_entry_datetime = newest_entry_datetime.rsplit(" ", maxsplit=1)[0]
entry_published = entry_published.rsplit(" ", maxsplit=1)[0]
dt_newest = datetime.datetime.strptime (newest_entry_datetime, "%a, %d %b %Y %H:%M:%S" )
st_entry = datetime.datetime.strptime (entry_published, "%a, %d %b %Y %H:%M:%S" )
if (st_entry <= dt_newest):
print('Entry date is older')
else:
print('Entry date is NEW')
Result is: 'Entry date is NEW' as it was expected.
If you compare you "dates" before converting to datetime - you compare strings. First you need convert to datetime (use for it right format if current is not support you string datetime style), and after that you can compare two datetime objects.
You can't convert to datetime to this format because of 'CET', for timezones you can you custom desicion (like this).
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