Jump to content

[Python]Date si ore in Python


iza
 Share

Recommended Posts

Exemplul 1: Python obtine data de astazi:

from datetime import date

today = date.today()
print("Today's date:", today)

Aici, am importat clasa de date din modulul datetime. Apoi, am folosit metoda date.today() pentru a obtine data locala curenta.

Apropo, date.today() returneaza un obiect de data, care este atribuit variabilei astazi din programul de mai sus. Acum, puteti utiliza metoda strftime() pentru a crea un sir care reprezinta data in diferite formate.

 

Exemplul 2: Data curenta in diferite formate:

from datetime import date

today = date.today()

# dd/mm/YY
d1 = today.strftime("%d/%m/%Y")
print("d1 =", d1)

# Textual month, day and year	
d2 = today.strftime("%B %d, %Y")
print("d2 =", d2)

# mm/dd/y
d3 = today.strftime("%m/%d/%y")
print("d3 =", d3)

# Month abbreviation, day and year	
d4 = today.strftime("%b-%d-%Y")
print("d4 =", d4)

Cand executati programul, iesirea va fi ceva de genul:

d1 = 16/09/2019
d2 = September 16, 2019
d3 = 09/16/19
d4 = Sep-16-2019

 

Daca trebuie sa obtineti data si ora curenta, puteti utiliza clasa datetime a modulului datetime.

 

Exemplul 3: Obtineti data si ora curenta:

from datetime import datetime

# datetime object containing current date and time
now = datetime.now()
 
print("now =", now)

# dd/mm/YY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)	

Iesire:

now = 2021-06-25 07:58:56.550604
date and time = 25/06/2021 07:58:56

Aici, am folosit datetime.now() pentru a obtine data si ora curenta. Apoi, am folosit strftime() pentru a face un sir care reprezinta data si ora intr-un alt format.

Link to comment
Share on other sites

  • Tupi locked this topic
Guest
This topic is now closed to further replies.
 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.