The Python Oracle

Datetime current year and month in Python

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Future Grid Looping

--

Chapters
00:00 Datetime Current Year And Month In Python
00:17 Answer 1 Score 315
00:30 Accepted Answer Score 183
00:44 Answer 3 Score 111
01:39 Answer 4 Score 17
01:44 Thank you

--

Full question
https://stackoverflow.com/questions/2818...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #datetime

#avk47



ANSWER 1

Score 315


Try this solution:

from datetime import datetime

current_second = datetime.now().second
current_minute = datetime.now().minute
current_hour = datetime.now().hour

current_day = datetime.now().day
current_month = datetime.now().month
current_year = datetime.now().year



ACCEPTED ANSWER

Score 183


Use:

from datetime import datetime
today = datetime.today()
datem = datetime(today.year, today.month, 1)

I assume you want the first of the month.




ANSWER 3

Score 111


Use:

from datetime import datetime

current_month = datetime.now().strftime('%m') # 02 This is 0 padded
current_month_text = datetime.now().strftime('%h') # Feb
current_month_text = datetime.now().strftime('%B') # February

current_day = datetime.now().strftime('%d')   # 23 This is also padded
current_day_text = datetime.now().strftime('%a')  # Fri
current_day_full_text = datetime.now().strftime('%A')  # Friday

current_weekday_day_of_today = datetime.now().strftime('%w') # 5  Where 0 is Sunday and 6 is Saturday.

current_year_full = datetime.now().strftime('%Y')  # 2018
current_year_short = datetime.now().strftime('%y')  # 18 without century

current_second= datetime.now().strftime('%S') # 53
current_minute = datetime.now().strftime('%M') # 38
current_hour = datetime.now().strftime('%H') # 16 like 4pm
current_hour = datetime.now().strftime('%I') # 04 pm

current_hour_am_pm = datetime.now().strftime('%p') # 4 pm

current_microseconds = datetime.now().strftime('%f') # 623596 Rarely we need.

current_timzone = datetime.now().strftime('%Z') # UTC, EST, CST etc. (empty string if the object is naive).

Reference: 8.1.7. strftime() and strptime() Behavior

Reference: strftime() and strptime() Behavior

The above things are useful for any date parsing, not only now or today. It can be useful for any date parsing.

e.g.

my_date = "23-02-2018 00:00:00"

datetime.strptime(str(my_date),'%d-%m-%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S+00:00')

datetime.strptime(str(my_date),'%d-%m-%Y %H:%M:%S').strftime('%m')

And so on...




ANSWER 4

Score 17


>>> from datetime import date
>>> date.today().month
2
>>> date.today().year
2020
>>> date.today().day
13