Få aktuellt datum med Python
Nödvändig förutsättning: DateTime-modul
I Python är datum och tid inte sina egna datatyper, men en modul med namnet DateTime kan importeras för att fungera med datumet och tiden. Datetime-modulen är inbyggd i Python, så det finns inget behov av att installera den externt. De DateTime-modul tillhandahåller vissa funktioner för att få aktuellt datum och tid.
Få det aktuella datumet med date.today()
Metoden today() för datumklass under DateTime-modulen returnerar ett datumobjekt som innehåller värdet för dagens datum.
Syntax: datum idag()
Returnerar: Returnera det aktuella lokala datumet.
Exempel:
Python3
# Import date class from datetime module> from> datetime> import> date> # Returns the current local date> today> => date.today()> print> (> 'Today date is: '> , today)> |
Produktion:
Today date is: 2019-12-11
Få det aktuella datumet med datetime.now()
Python-biblioteket definierar en funktion som främst kan användas för att få aktuell tid och datetime.now() funktion och returnerar det aktuella lokala datumet och tiden, som definieras under modulen DateTime.
Syntax: datetime.now(tz)
Parametrar: tz: Angiven tidszon för vilken aktuell tid och datum krävs. (Använder Greenwich Meridian-tid som standard.) Returnerar: Returnerar aktuellt datum och tid i tidsformat.
Exempel:
Python3
# Import datetime class from datetime module> from> datetime> import> datetime> # returns current date and time> now> => datetime.now()> print> (> 'now = '> , now)> |
Produktion:
now = 2019-12-11 10:58:37.039404
Attribut för nu()
Now() har olika attribut, samma som attribut för tid som år, månad, datum, timme, minut och sekund.
Exempel
Python3
# importing datetime module for now()> import> datetime> > # using now() to get current time> current_time> => datetime.datetime.now()> > # Printing attributes of now().> print> (> 'The attributes of now() are : '> )> > print> (> 'Year: '> , end> => '')> print> (current_time.year)> > print> (> 'Month: '> , end> => '')> print> (current_time.month)> > print> (> 'Day: '> , end> => '')> print> (current_time.day)> |
Produktion:
The attributes of now() are: Year: 2019 Month: 12 Day: 11
REKOMMENDERADE ARTIKLAR – Få aktuellt datum och tid med Python