Reputation: 3
How can I convert a date into a numeric date?
For example, I want to convert '06-Jun-2021'
to '20210609'
and then turn it into a string i can use in a webpage eg. baseball.theater/games/20210609
so that i can automate the process daily.
using datetime i've managed to do :
print (todays_date.year,todays_date.month,todays_date.day,sep="")
which can print the output i need (without the trailing 0's) but i cannot make this into a string which i can use.
obviously i am a COMPLETE newcomer to python, so be gentle please.
Upvotes: 0
Views: 1527
Reputation: 59
I think you are looking time.strftime()
The function needs time module
import time
then you can either use a variable and display that time in a specific format.
t = time.time()
print(time.strftime('%H%M%S', t) # print the time t in specific format
print(time.strftime('%H%M%S') # print present time in specific format
Here is a list of options from https://www.tutorialspoint.com/
Upvotes: -1
Reputation: 117886
You can use datetime.strptime
to turn a string into a datetime
object, then datetime.strftime
to reformat it into a different string.
>>> from datetime import datetime
>>> s = '06-Jun-2021'
>>> dt = datetime.strptime(s, '%d-%b-%Y')
>>> dt.strftime('%Y%m%d')
'20210606
For the specific case of the current day, you can use datetime.today
>>> datetime.today().strftime('%Y%m%d')
'20210609'
To combine this into your final string you can use str.format
>>> 'baseball.theater/games/{}'.format(datetime.today().strftime('%Y%m%d'))
'baseball.theater/games/20210609'
Upvotes: 4
Reputation: 177
Here, just typecast it to str and use .replace() method
from datetime import date # datetime is a built-in module
today = str(date.today())
string = today.replace("-", "")
print(string)
P.S Just providing an alternate method to strftime
Upvotes: -1