Converting date in python - python

I need to convert dates that look like this "2/28/2012" into Feb 28, 2012.
Anyone know how to do this using string slicing, split, and datetime?

Just using datetime.datetime:
from datetime import datetime
date_str = '2/28/2014'
new_date_str = datetime.strptime(date_str, '%m/%d/%Y').strftime('%b %d, %Y')
>>> print new_date_str
Feb 28, 2014
strptime() parses the date string into a datetime.datetime object. strftime() converts that datetime back to a string in the required format.
If you want to do it with string operations:
months = {'1': 'Jan', '2': 'Feb', '3': 'Mar', ...., '12': 'Dec'}
date_str = '2/28/2014'
month, day, year = date_str.split('/')
new_date_str = '{} {}, {}'.format(months[month], day, year)

Yes you can. Try something like this...
from calendar import month_abbr
dateNonFormat = "2/28/2012"
splitDate = dateNonFormat.split("/")
monthFormatted = month_abbr[int(splitDate[0])]
formattedDate = "%s %s, %s" % (monthFormatted, s[1], s[2])
In this example your formatted date would be Feb 28, 2012

You can use easy_date to make it easy:
import date_converter
my_datetime = date_converter.string_to_string('2/28/2012', '%m/%d/%Y', '%b %d, %Y')

Related

How to input current time in python

I need some help on datetime
here is my code:
import datetime
x = int(input()).datetime.datetime()
print(x.strftime("%B, %d, %Y"))
My custom input: 12 25 1990
but I always got an error ValueError: invalid literal for int() with base 10: '12 25 1990'
I just wanted the output to be " December 25, 1990" can anybody help thank you;;
As #Barmar suggested, use datetime.strptime:
import datetime
x = datetime.datetime.strptime(input(), '%m %d %Y')
print(x.strftime("%B %d, %Y"))
output (for input 12 25 1990)
December 25, 1990
You have two options either prepare the datetime object by splitting the input and preparing date, month, etc. as:
import datetime
date_entry = '12 25 1990'
month, day, year = map(int, date_entry.split())
x = datetime.date(year, month, day)
print(x.strftime("%B, %d, %Y"))
Or simply use strptime to create the date from the input format as:
date_entry = '12 25 1990'
res = datetime.datetime.strptime(date_entry, '%m %d %Y')
print(res.strftime("%B, %d, %Y"))

how to convert date to mysql format in python

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)

How do I convert string date to datetime?

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

Parsing date string with year omitted

I am given a series of date strings of the format 'July 24', i.e. '%B %d'. I would like to parse these strings such that the year corresponds to the most recent date, so if today is July 24, 2019 then 'July 24' should be parsed as 24/7/2019 but 'July 25' should be parsed as 25/7/2018. I was hoping that the datetime module could do this, but it just sets the year to 1900.
>>> from datetime import datetime
>>> datetime.strptime('July 24', '%B %d')
datetime.datetime(1900, 7, 24, 0, 0)
Is there an easier way to achieve this than to manually parse the dates according to my rule?
Can be done in a single line, and I won't be surprised if there's an even easier way:
from datetime import datetime
today = datetime.today()
before = datetime.strptime('July 24', '%B %d')
print(before.replace(year=today.year if before.replace(year=1) <= today.replace(year=1) else today.year - 1))
after = datetime.strptime('July 25', '%B %d')
print(after.replace(year=today.year if after.replace(year=1) <= today.replace(year=1) else today.year - 1))
Outputs
2019-07-24 00:00:00
2018-07-25 00:00:00
Of course this can be micro-optimized by not calling before.replace (or after.replace) twice, but as an example this is good enough.
One thing that comes to mind about this issue is that datetime.datetime has 'year' as it's first positional argument, which is required to create an actual instance of it. So if you import the class datetime.dateime as datetime and make reference to it's methods without first delcaring an instance of it, then you are relying on the default values of attribs like datetime.datetime.year.
Here is a function that accepts a string, mydate, whose format is "%B %d", and returns a datetime instance with it's year attribute set to 2019 (but keeping month and day the same) if datetime.datetime.today().month == datetime.datetime.strptime(mydate, "%B %d").month and datetime.datetime.today().day == datetime.datetime.strptime(mydate, "%B %d").day, or with it's year attribute set to 2018 in any other case.
You can call strftime("%Y/%B/%d") to get the string for further along in your greater procedure, or ad it to this definition.
import datetime
def make_year_float(mydate):
dt = datetime.datetime
d1 = dt.today().month, dt.today().day
the_date = dt.strptime(mydate, "%B %d")
d2 = the_date.month, the_date.day
if d1 == d2:
return dt(2019, the_date.month, the_date.day)
elif d1 != d2:
return dt(2018, the_date.month, the_date.day)

Convert date from mm/dd/yyyy to another format in Python

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

Categories

Resources