Python Forum
Function to return today's month, day, and year
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Function to return today's month, day, and year
#1
function current_date to return today's month, day, and year



def c_date():
    pass
    #TODO return month, day, year

m, d, y = c_date()            [b]#How do I pass the date into c_date function here?[/b]
print("Today's date is: {:2d}/{:2d}/{:4d}".format(m, d, y))
Quote:Tried the as below it did not work


from datetime import date
dt = date.today()
m = dt.month()
print(m)

#def c_dt():
#    dt = date.today()
 #   m = dt.month()
  #  d = dt[1:2]
   # y = dt[:-1]
    
#c_dt()

#print("Today's date is: {:2d}/{:2d}/{:4d}".format(m, d, y))
Reply
#2
To get year, month and day from datetime.date one can just:

>>> date.today().year                                                                                                                   
2020
>>> date.today().month                                                                                                                  
1
>>> date.today().day                                                                                                                    
27
However, date can't be unpacked directly, because it's not iterable:

>>> year, month, day = date.today()                                                                                                     
/.../
TypeError: cannot unpack non-iterable datetime.date object
However, there is method .timetuple which can be used for unpacking. As it returns more values than we need one could use *:

>>> year, month, day, *_ = date.today().timetuple()                                                                                     
>>> year                                                                                                                                
2020
>>> month                                                                                                                               
1
>>> day                                                                                                                                 
27
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
To get my local date I use

import locale
import datetime

loc = locale.getlocale()
locale.setlocale(locale.LC_ALL, loc)
dt = datetime.date.today().strftime("%-d.%B %Y")
dt2 = datetime.date.today().strftime("%-d.%m.%Y")
print(dt)
print(dt2)
Output:
27.Januar 2020 27.01.2020
Reply
#4
(Jan-27-2020, 08:47 AM)Axel_Erfurt Wrote: To get my local date I use

Local language, but not local timezone.
To handle timezone without headache: pendulum
Before I used pytz, but the headache-factor is bigger.

You can do this also with the datetime-module, but it's not easy to handle it right.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
is this better?

import locale
import datetime
from dateutil.tz import tzlocal

loc = locale.getlocale()
locale.setlocale(locale.LC_ALL, loc)
print("LOCALE:", loc)

ltz = datetime.datetime.now(datetime.timezone(datetime.timedelta(0))).astimezone().tzinfo
print("LOCAL TIMEZONE:", ltz)


local = tzlocal()
now = datetime.datetime.now(tz=ltz)
now = now.replace(tzinfo = local)

print(now)
print(now.strftime("%-d.%B %Y %H:%M"))
print(now.strftime("%-d.%m.%Y %H:%M"))
Output:
LOCALE: ('de_DE', 'UTF-8') LOCAL TIMEZONE: CET 2020-01-27 13:15:04.439200+01:00 27.Januar 2020 13:15 27.01.2020 13:15
Reply
#6
def cdt():
    from datetime import date
    y = date.today().year
    m = date.today().month
    d = date.today().day
    return y,m,d
    
cdt()

print("Today's date is: {:2d}/{:2d}/{:4d}".format(m, d, y))
Getting this error

print("Today's date is: {:2d}/{:2d}/{:4d}".format(m, d, y))
NameError: name 'm' is not defined

####################################################################

How do I create this type of function

def c_date():
    from datetime import date
    y = date.today().year
    m = date.today().month
    d = date.today().day
    return y,m,d
 

m, d, y = c_date()

#####################################################
# How do I use these m,d,y while calling the function ???
######################################################




Thanks u all
Reply
#7
Without assigning names to what function returns there is nothing to refer in print statement. y, m, d are not visible outside the function. You should assign names if you call the function to use in print statement:

>>> y, m, d = cdt()
>>> print("Today's date is: {:02d}/{:02d}/{:4d}".format(d, m, y))    # note zero in day and month formatting                                                                     
Today's date is: 28/01/2020
You can change the order of returning values and unpack it while printing (without assigning to names):

# in function change 'return y, m, d' --> 'return d, m, y'
>>>  print("Today's date is: {:02d}/{:02d}/{:4d}".format(*cdt()))
Today's date is: 28/01/2020 
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#8
Thank u all
Reply
#9
shorter

from datetime import date

def cdt():
    d = date.today()
    return d.strftime("%m/%d/%Y")
     
td = cdt()
print(f"Today's date is: {td}")
Output:
Today's date is: 01/28/2020
Reply
#10
(Jan-28-2020, 11:10 AM)Axel_Erfurt Wrote: shorter
Can also drop strftime and let f-string do all the job Wink
>>> from datetime import date
>>>
>>> print(f"Today's date is: {date.today():%m/%d/%Y}")
Today's date is: 01/28/2020
(Jan-28-2020, 11:10 AM)Axel_Erfurt Wrote: is this better?
Yes,but Pendulum as mention bye @DeaD_EyE dos this better.
Can trow away a combination of datetime, dateutil, pytz ..ect,and use pendulum that dos Timezone correct.
>>> import pendulum
>>> 
>>> now = pendulum.now()
>>> now
DateTime(2020, 1, 28, 19, 15, 24, 146775, tzinfo=Timezone('Europe/Berlin'))
>>> print(now)
2020-01-28T19:15:24.146775+01:00
>>>
>>> now.timezone
Timezone('Europe/Berlin')
>>> now.is_utc()
False
>>>
>>> future = now.add(years=1)
>>> future
DateTime(2021, 1, 28, 19, 15, 24, 146775, tzinfo=Timezone('Europe/Berlin'))
>>> future.diff_for_humans()
'in 1 year' 
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Use of function/return Paulman 6 2,340 Oct-24-2021, 11:07 PM
Last Post: Paulman
  Multiple return from function Grimmar 7 3,512 Mar-22-2021, 09:20 PM
Last Post: Grimmar
  Lambda function not return value mbilalshafiq 4 3,286 Jul-04-2020, 07:47 AM
Last Post: ndc85430
  Child class function of Log return "None" mbilalshafiq 2 2,204 Jun-30-2020, 07:22 PM
Last Post: mbilalshafiq
  Question on "define function"; difference between return and print extricate 10 4,651 Jun-09-2020, 08:56 PM
Last Post: jefsummers
  [split] problem with function return value ops 1 3,329 Apr-13-2020, 01:48 PM
Last Post: buran
  return outside function seamus 4 3,035 May-17-2019, 07:38 PM
Last Post: seamus
  Recursive Function - Compare 2 lists, return the elements that don't exist in both KellyBaptist 1 5,212 Dec-23-2018, 10:10 AM
Last Post: Gribouillis
  Need of return in function if statement inside the function already returns Athul 5 3,910 Aug-16-2018, 10:19 AM
Last Post: DuaneJack
  Calling function-- how to call simply return value, not whole process juliabrushett 2 3,189 Jul-01-2018, 01:17 AM
Last Post: juliabrushett

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020