I have a question: How to use "strip" function to slice a date like "24.02.1999"?
The output should be like this '24', '02', '1999'.
Can you help to solve this?
You can do like this
>>> stri="24.02.1999"
>>> stri.split('.')
['24', '02', '1999']
>>>
strip is used to remove the characters. What you meant is split. For your code,
date = input('Enter date in the format (DD.MM.YY) : ')
dd, mm, yyyy = date.strip().split('.')
print('day = ',dd)
print('month = ',mm)
print('year = ',yyyy)
Output:
Enter date in the format (DD.MM.YY) : 24.02.1999
day = 24
month = 02
year = 1999
You need to use split() not strip().
strip() is used to remove the specified characters from a string.
split() is used to split the string to list based on the value provided.
date = str(input()) # reading input date in dd.mm.yyyy format
splitted_date = date.split('.') # splitting date
day = splitted_date[0] # storing day
month = splitted_date[1] # storing month
year = splitted_date[2] # storing year
# Display the values
print('Date : ',date)
print('Month : ',month)
print('Year : ',year)
You can split date given in DD.MM.YYYY format like this.
Instead of splitting the string, you should be using datetime.strptime(..) to convert the string to the datetime object like:
>>> from datetime import datetime
>>> my_date_str = "24.02.1999"
>>> my_date = datetime.strptime(my_date_str, '%d.%m.%Y')
Then you can access the values you desire as:
>>> my_date.day # For date
24
>>> my_date.month # For month
2
>>> my_date.year # For year
1999
Here you go
date="24.02.1999"
[dd,mm,yyyy] = date.split('.')
output=(("'%s','%s','%s'") %(dd,mm,yyyy))
print(output)
alternate way
date="24.02.1999"
dd=date[0:2]
mm=date[3:5]
yyyy=date[6:10]
newdate=(("'%s','%s','%s'") %(dd,mm,yyyy))
print(newdate)
one more alternate way
from datetime import datetime
date="24.02.1999"
date=datetime.strptime(date, '%d.%m.%Y')
date=(("'%s','%s','%s'") %(date.day,date.month,date.year))
print(date)
Enjoy
Related
How would I go about designing a Python program which takes in a date from the user, a date that looks like this 3/13/17, and turns it into a date which looks like this 2017.3.13?
You can split the string by using the str.split method like this:
s = "3/13/17"
month, day, year = s.split("/")
print(f"20{year}.{month}.{day}")
Python will automatically assign the splitted values to the variables month, day, and year
Get the date as text and then convert it to date with the format you would like. or get the date as a number (month, date and year ) separately and make it as a date.
Example:
my_string = str(input('Enter date(yyyy-mm-dd): '))
my_date = datetime.strptime(my_string, "%Y-%m-%d")
I have a list of dates.
['1/12/2022', '1/13/2022','1/17/2022']
How do I reformat them to look like this:
['2022-1-12', '2022-1-13','2022-1-17']
EDIT: My original post asked about the wrong format. I've corrected it because I meant for the the format to be "Year-Month-Day"
I am assuming you are using Python... Please correct me if I am wrong. You can loop through the list of dates using a enumerated for-loop (enumerate(list) function lets you know the index of each value during the loop) with each date, use the .replace() method of str to replace '/' with '-' like this:
list_of_dates = ['1/12/2022', '1/13/2022','1/17/2022']
for i, date in enumerate(list_of_dates):
list_of_dates[i] = date.replace('/', '-')
or use list comprehension like this (thank you #Eli Harold ):
list_of_dates = [date.replace('/', '-') for date in list_of_dates]
If you want to change the order of the numbers in the date string you can split them by the '/' or '-' into a new list and change the order if you want like this:
for i, date in enumerate(list_of_dates):
month, day, year = date.split('-') # assuming you already changed it to dashes
list_of_dates[i] = f'{day}-{month}-{year}'
you can use strptime
from datetime import datetime
dates = []
for date_str in ['1/12/2022', '1/13/2022','1/17/2022']:
date = datetime.strptime(date_str, '%m/%d/%Y')
dates.append(date.strftime('%m-%d-%Y'))
I opted to split the individual dates and then add in the "-" delimiter after the fact, but you could also replace those on iteration. Once your data has been transformed, I just pushed it into a new list of reformatted dates.
This may not result in the best performance for longer iterations, though.
dates = ['1/12/2022', '1/13/2022','1/17/2022']
newdates = []
for x in range(0, len(dates)):
split_date = dates[x].split('/')
month = split_date[0]
day = split_date[1]
year = split_date[2]
your_date = year +"-"+month+"-"+day
newdates.apppend(your_date)
print(your_date)
And the output:
2022-1-12
2022-1-13
2022-1-17
from datetime import datetime
dates = [datetime.strptime(x, "%-m/%-d/%Y") for x in list_of_dates]
new_dates = [x.strftime("%Y-%-m-%-d") for x in dates]
dates = ['1/12/2022', '1/13/2022','1/17/2022']
dates = [x.replace('/', '-') for x in dates]
I'm trying to do something like
date = "9/26/2017"
for %m in date:
%m = i
print(format(i, '02d'))
Is there a way to get the month number so that I can put a 0 in front of it?
I'm trying to take 9/26/2017 and output 09/26/2017.
from datetime import *
d = '9/26/2017'
d = datetime.strptime(d,'%m/%d/%Y').date()
d = datetime.strftime(d,'%m/%d/%Y')
print d
09/26/2017
you can split and zero-pad all fields in one line using format and unpacking arguments from conversion to integer of your splitted string:
"{:02}/{:02}/{:04}".format(*map(int,date.split("/")))
note: for only the first number, you could have used date.zfill(10) or to apply zfill on all terms with varying sizes:
"/".join(a.zfill(b) for a,b in zip(date.split("/"),[2,2,4]))
If you r reading date in the format you mentioned, then use
date = "9/26/2017"
d = date.split("/")
if len(d[0])==1:
date="0"+date
print(date)
Below is my data set
Date Time
2015-05-13 23:53:00
I want to convert date and time into floats as separate columns in a python script.
The output should be like date as 20150513 and time as 235300
If all you need is to strip the hyphens and colons, str.replace() should do the job:
>>> s = '2015-05-13 23:53:00'
>>> s.replace('-', '').replace(':', '')
'20150513 235300'
For mort sophisticated reformatting, parse the input with time.strptime() and then reformat with time.strftime():
>>> import time
>>> t = time.strptime('2015-05-13 23:53:00', '%Y-%m-%d %H:%M:%S')
>>> time.strftime('%Y%m%d %H%M%S', t)
'20150513 235300'
If you have a datetime you can use strftime()
your_time.strftime('%Y%m%d.%H%M%S')
And if your variables are string, You can use replace()
dt = '2015-05-13 23:53:00'
date = dt.split()[0].replace('-','')
time = dt.split()[1].replace(':','')
fl = float(date+ '.' + time)
date = "2015-05-13".replace("-", "")
time = "10:58:56".replace(":", "")
I am new to python and only know the most basic level.
I am supposed to allow input of a date in the form of dd/mm/yyyy and convert it to something like 26 Aug, 1986.
I am stuck as to how to convert my month(mm) from numbers to words.
Below is my current code, hope you can help me.
** please do not suggest using calendar function, we are supposed to use dict to solve this question.
Thank you (:
#allow the user to input the date
date=raw_input("Please enter the date in the format of dd/mm/year: ")
#split the strings
date=date.split('/')
#day
day=date[:2]
#create a dictionary for the months
monthDict={1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}
#month
month=date[3:5]
if month in monthDict:
for key,value in monthDict:
month=value
#year
year=date[4:]
#print the result in the required format
print day, month, "," , year
Use Python's datetime.datetime! Read using my_date = strptime(the_string, "%d/%m/%Y"). Print it using my_date.strftime("%d %b, %Y").
Visit: http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
Example:
import datetime
input = '23/12/2011'
my_date = datetime.datetime.strptime(input, "%d/%m/%Y")
print my_date.strftime("%d %b, %Y") # 23 Dec, 2011
date = raw_input("Please enter the date in the format of dd/mm/year: ")
date = date.split('/')
day = date[0] # date is, for example, [1,2,1998]. A list, because you have use split()
monthDict = {1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun',
7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}
month = date[1] # Notice how I have changed this as well
# because the length of date is only 3
month = monthDict[int(month)]
year = date[2] # Also changed this, otherwise it would be an IndexError
print day, month, "," , year
When run:
Please enter the date in the format of dd/mm/year: 1/5/2004
1 May , 2004
After you have done split, you don't need to use index like day=date[:2]. Simply use say = date[0]. Similarly no looping is required to match dictionary values. You can see the code below.
#allow the user to input the date
date=raw_input("Please enter the date in the format of dd/mm/year: ")
#split the strings
date=date.split('/')
#day
day=date[0]
#create a dictionary for the months
monthDict={1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}
#month
monthIndex= int(date[1])
month = monthDict[monthIndex]
#year
year=date[2]
print day, month, "," , year
When you split your date string, you will only have three elements (0, 1, and 2):
>>> date=date.split('/')
>>> print date
['11', '12', '2012']
^ ^ ^
0 1 2
Thus, date[:2] will equal this:
>>> day=date[:2] # that is, date up to (but not including) position 2
>>> print day
['11', '12']
And date[4] will not exist, and neither will date[3:5].
In addition, you need to call your dictionary value like this:
>>> print monthDict[12]
Dec
So to print the day, month, year combination, you would want to do this:
>>> print date[0], monthDict[int(date[1])] + ", " + date[2]
11 Dec, 2012
You have to use int(date[0]) as your key in monthDict[int(date[0])] because you used integers as your dictionary keys. But your input (from the user) is a string, not integers.