Use strftime:
>>> from datetime import datetime
>>> datetime.today().strftime('%Y-%m-%d')
'2021-01-26'
To also include a zero-padded Hour:Minute:Second at the end:
>>> datetime.today().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-26 16:50:03'
To get the UTC date and time:
>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-27 00:50:03'
Answer from diegueus9 on Stack OverflowUse strftime:
>>> from datetime import datetime
>>> datetime.today().strftime('%Y-%m-%d')
'2021-01-26'
To also include a zero-padded Hour:Minute:Second at the end:
>>> datetime.today().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-26 16:50:03'
To get the UTC date and time:
>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-27 00:50:03'
You can use datetime.date.today() and convert the resulting datetime.date object to a string:
from datetime import date
today = str(date.today())
print(today) # '2017-12-26'
Videos
I'm a student working on a Python project. In my code, I have a global variable:
today = date.today()
I am concerned with the date only, meaning I don't use time in my program. The only reason I would be concerned about time is for when it causes one today's date to switch to tomorrow's date.
Throughout my code, I reference this variable a bunch of times. For example:
-
today.day to get the current day of the month
-
today.strftime("%B") to get the current month name
-
today.year to get the current year, etc.
Recently, I have realized I need to deal with timezones. Upon looking up how to do this, I found some guides on how to use pytz. It seems fairly straightforward, however it all has to do with datetime.now() instead of date.today(), which I have been using throughout my code. I was hoping I could just swap in datetime.now(), but it messes things up because it has the date and the time, instead of just the date.
What is my best course of action? Is there a way for me to get date.today() to work with timezones/pytz, or do I need to re-work my code so that it can work with datetime.now()?
Hopefully this all makes sense. I just learned Python a few months ago. Thanks.