Convert date from mm/dd/yyyy to another format in Python - 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

Related

How can I change this format to be datetime format? (python)

I have a dataset which contains some columns with datetime. My problem is, I found this type datetime format:
Apr'11
Apr-11
Apr 11
How can I automatically change this format to be datetime format?
for you can use datetime module
from datetime import datetime
this is the link if you want any confusion
date_string = "Apr'11"
date = datetime.strptime(date_string, "%b'%d")
%b = Locale’s abbreviated month name. (like Apr, Mar, Jan, etc)
%d = Day of the month as a decimal number [01,31]
date_string_2 = "Apr-11"
date = datetime.strptime(date_string, "%b-%d")
date_string_3 = "Apr 11"
date = datetime.strptime(date_string, "%b %d")
You should write this "%b %d" same as like date_string otherwise it will give you, even if you give an extra space.
go to this link to learn more about this:
https://docs.python.org/3/library/time.html

get hours from full date date to python3

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

Format Unicode time value

I have next time value in unicode (<type 'unicode'>):
2017-08-09T15:02:58+0000.
How to convert it to friendly view (e.g. Day, Month of Year)?
This should do what you ask:
from datetime import datetime
a = '2017-08-09T15:02:58+0000'
datetime.strptime(a[:-5], '%Y-%m-%dT%H:%M:%S').strftime('%d, %b of %Y')
#09, Aug of 2017
strptime method throws error for timezone parameter that doesn't seem to interest you so I removed that part with a[:-5].
For the rest of the string you can just follow guidelines from datetime docs.
Using the same docs you can construct your datetime string using strftime() method like you wanted '%d, %b of %Y' or in plain words [day], [abbreviated month] of [Year]
try this
import datetime
today = datetime.date.today()
print today.strftime('We are the %d, %b %Y')
'We are the 22, Nov 2008'

Convert timestring into date - Python

If I have the following timestring:
20150505
How would I convert this into the date May 5, 2015 in Python? So far I've tried:
from datetime import datetime
sd = datetime.strptime('20150504', '%Y%M%d')
But this outputs:
2015-01-04 00:05:00
The capital M denotes minute not month. Use the lowercase m and then call the strftime method to refactor the format:
>>> datetime.strptime('20150504', '%Y%m%d').strftime('%b %d, %Y')
'May 04, 2015'
You can remove the zero padding from the month by using the -d directive in place of d:
%-d Day of the month as a decimal number. (Platform specific)
For longer month names, you can use the directive %B in place of %b to get the full month name.
Reference:
http://strftime.org/
If you know it's a date and not a datetime, or you don't know the format. You can use dateutil.
from dateutil.parser import parse
print(parse('20150504'))
This is the anwser, wihout leading zero for day, as OP's example:
print(sd.strftime('%b %-d, %Y'))
# Jan 4, 2015 # note your sd parsing is wrong. Thus Jan

Convert date to natural language in python? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to print date in a regular format in Python?
I would like to know how to convert the following date to natural language, including time zone in python?
input:
"'2012-09-27T02:00:00Z'"
expected output:
Wednesday, September 26 of 2012 Mountain Time
Thanks in advance!
Note Edit:
So far I tried django humanize, although it doesn't handle very well complex date-time strings.
Solution:
Thanks for all the information. I ended up parsing the original string and using pitz and strftime like this:
my_date = '2012-09-27T02:00:00Z'
utc_date_object = datetime(int(my_date[0:4]), int(my_date[5:7]), int(my_date[8:10]),int(my_date[11:13]),int(my_date[14:16]),int(my_date[17:19]),0,pytz.utc)
mt_date_object = utc_date_object.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('US/Mountain'))
natural_date = mt_date_object.strftime("%A, %B %d of %Y")
Output:
'Wednesday, September 26 of 2012'
The Babel project offers a full-featured date and time localization library.
You'll also need the iso8601 module to parse a date-time string with a timezone correctly.
It either formats dates and times based on locale:
>>> from datetime import date, datetime, time
>>> from babel.dates import format_date, format_datetime, format_time
>>> d = date(2007, 4, 1)
>>> format_date(d, locale='en')
u'Apr 1, 2007'
>>> format_date(d, locale='de_DE')
u'01.04.2007'
or it let's you specify the format in detail. This includes formatting the timezone.
Putting the parser and the formatter together:
>>> dt = iso8601.parse_date("2012-08-25T02:00:00Z")
>>> format_date(dt, "MMMM dd, yyyy", locale='en') + ' at ' + format_time(dt, "HH:mm V")
u'August 25, 2012 at 02:00 World (GMT) Time'
Ordinals ('1st', '2nd', etc.) are a little harder to do internationally, and the LDML format used by Babel doesn't include a pattern for these.
If you must have an ordinal in your date formatting (perhaps because you only expect to output in English), you'll have to create those yourself:
>>> suffix = ('st' if dt.day in [1,21,31]
... else 'nd' if dt.day in [2, 22]
... else 'rd' if dt.day in [3, 23]
... else 'th')
>>> u'{date}{suffix}, {year} at {time}'.format(
... date=format_date(dt, "MMMM dd", locale='en'),
... suffix=suffix, year=dt.year,
... time=format_time(dt, "HH:mm V"))
u'August 25th, 2012 at 02:00 World (GMT) Time'
You can get a custom string representation of your date using the strftime() method. strftime accepts a string pattern explaining how you want to format your date.
For example:
print today.strftime('We are the %d, %h %Y')
'We are the 22, Nov 2008'
All the letters after a "%" represent a format for something:
%d is the day number
%m is the month number
%y is the year last two digits
%Y is the all year
https://stackoverflow.com/a/311655
Not 100% the answer to your question, but this code might help you starting formatting time and date:
import datetime
print datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S')
def myFormat(dtime):
if dtime.day in [1,21,31] : ending = "st"
elif dtime.day in [2,22] : ending = "nd"
elif dtime.day in [3,23] : ending = "rd"
else : ending = "th"
return dtime.strftime("%B %d"+ ending + " of %Y")

Categories

Resources