Python DateTime, TimeDelta, Strftime(Format) s příklady

⚡ Chytré shrnutí

Python datetime, along with the date, time, and timedelta classes, handles dates, times, and intervals as objects. The datetime module formats output with strftime(), parses strings, and calculates future or past moments using timedelta arithmetic.

  • 🔘 Five classes: The datetime module groups the date, time, datetime, timedelta, and tzinfo classes for date and time work.
  • ☑️ Current values: datetime.now() and date.today() return the present date and time, including the weekday number.
  • (Tj. Formátování: The strftime() function turns a datetime into readable text using control codes such as %Y, %A, and %H.
  • 🧪 Timedelta: A timedelta object measures a duration and predicts future or past dates through addition and subtracvání.
  • 🛠️ Směrnice: The same control codes drive strftime() for output and strptime() for reading a string back into a datetime.
  • 🤖 Pracovní postupy umělé inteligence: Machine learning pipelines derive datetime features such as weekday and hour for time-series models.

Python Čas schůzky

In Python, datum, čas a datum a čas classes provide a number of functions to deal with dates, times and time intervals. Date and datetime in Python are objects, so when you manipulate them, you are actually manipulating objects and not strings or timestamps. Whenever you manipulate dates or time, you need to import the datetime module.

Kurzy podle data a času v Python are categorized into 5 main classes.

  • datum – manipulace pouze s datem (měsíc, den, rok)
  • čas – Čas nezávislý na dni (hodina, minuta, sekunda, mikrosekunda)
  • datetime – kombinace času a data (měsíc, den, rok, hodina, sekunda, mikrosekunda)
  • timedelta— Doba trvání času používaná pro manipulaci s daty
  • tzinfo— Břišní svalytractřída t pro práci s časovými pásmy

Jak používat třídu Date & DateTime

Krok 1) Než spustíte kód pro formát data a času v Python, je důležité, abyste importovali soubor Python moduly data a času, jak je znázorněno na obrázku níže.

Použijte třídu Date & DateTime

Tyto příkazy importu jsou předdefinovanými částmi funkcí v Python library that let you manipulate dates and times, without writing any code.

Před provedením zvažte následující body Python kód formátu data a času

from datetime import date

Tento řádek říká Python interpret pro import třídy data z modulu datetime do Python. We are not writing the code for this date functionality but are simply importing it for our use.

Vytisknout datum pomocí date.today()

The date.today() function has several properties associated with it. We can print the individual day/month/year and many other things.

Podívejme se na příklad

Vytisknout datum pomocí date.today()

Dnešní číslo dne v týdnu

The date.today() function also gives you the weekday number. Here is the Weekday Table which starts with Monday as 0 and Sunday as 6.

Den Číslo dne v týdnu
Monday 0
Úterý 1
Středa 2
Čtvrtek 3
Pátek - Sobota 4
Sobota 5
NEDĚLE 6

Weekday Number je užitečné pro pole, jejichž index závisí na dni v týdnu.

Vytisknout datum pomocí date.today()

Krok 2) Dále vytvoříme instanci objektu date.

Použijte třídu Date & DateTime

Krok 3) Dále vytiskneme datum a spustíme kód.

Použijte třídu Date & DateTime

The output is as expected.

Python Aktuální datum a čas: nyní() dnes()

Krok 1) Stejně jako Date Objects můžeme také použít "OBJECTS DATETIME" in Python. Python objekty data a času dávají datum spolu s časem v hodiny, minuty, sekundy a milisekundy.

Python Aktuální datum a čas

Když spustíme kód pro datum a čas, poskytne výstup s aktuálním datem a časem.

Krok 2) With “DATETIME OBJECT”, you can also call the time class. Suppose we want to print just the current time without the date.

t = datetime.time(datetime.now())
  • Časovou třídu jsme importovali. Přiřadíme mu aktuální hodnotu času pomocí datetime.now()
  • Proměnné t přiřazujeme hodnotu aktuálního času.

A tohle mi dá akorát čas. Pojďme tedy spustit tento program.

Python Aktuální datum a čas

Okay, so you can see that here I got the date and time. And then the next line, I’ve got just the time by itself.

Krok 3) We will apply our weekday indexer to our weekday’s array list to know which day is today.

  • Weekdays operator (wd) is assigned the number from (0-6) depending on what the current weekday is. Here we declared the array of the list for days (Mon, Tue, Wed…Sun).
  • Pomocí této hodnoty indexu zjistíte, který den je. V našem případě je to #2 a představuje středu, takže na výstupu se vypíše „Co je středa“.

Python Aktuální datum a čas

Zde je úplný kód pro získání aktuálního data a času pomocí datetime nyní

from datetime import date
from datetime import time
from datetime import datetime
def main():
    ##DATETIME OBJECTS
    #Get today's date from datetime class
    today=datetime.now()
    #print (today)
    # Get the current time
    #t = datetime.time(datetime.now())
    #print "The current time is", t
    #weekday returns 0 (monday) through 6 (sunday)
    wd=date.weekday(today)
    #Days start at 0 for monday
    days= ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
    print("Today is day number %d" % wd)
    print("which is a " + days[wd])

if __name__== "__main__":
    main()

Jak formátovat výstup data a času pomocí Strftime()

So far, we have learned how to use datetime and date objekt v Python. Postoupíme o krok dále a naučíme se, jak používat funkci formátování k formátování času a data.

Krok 1) Nejprve uvidíme jednoduchý krok, jak formátovat rok. Lépe je to pochopit na příkladu.

Formátovat výstup data a času pomocí Strftime()

  • Použili jsme “strftime function” pro formátování.
  • Tato funkce používá různé kontrolní kód dát výstup.
  • Each control code resembles different parameters like year, month, weekday and date [(%y/%Y – rok), (%a/%A- den v týdnu), (%b/%B- měsíc), (%d – den v měsíci)] .
  • V našem případě ano („%Y“) který připomíná rok, vytiskne celý rok se stoletím (např. 2018).

Krok 2) Nyní, pokud nahradíte (“%Y”) malými písmeny, tj. ( “%y) a provedete kód, výstup zobrazí pouze (18) a ne (2018). Století roku se nezobrazí tak, jak je znázorněno na snímku obrazovky níže

Formátovat výstup data a času pomocí Strftime()

Krok 3) Strf function can declare the date, day, month and year separately. Also with small changes in the control code in strftime function you can format the style of the text.

Formátovat výstup data a času pomocí Strftime()

Inside the strftime function if you replace (%a) with capital A, i.e., (%A) the output will print out as “Friday” instead of just an abbreviation “Fri”.

Formátovat výstup data a času pomocí Strftime()

Krok 4) Pomocí funkce „Strftime“ můžeme také získat místní systémový čas, datum nebo obojí.

  1. %C- označuje místní datum a čas
  2. %x- označuje místní datum
  3. %X- označuje místní čas

Formátovat výstup data a času pomocí Strftime()

Ve výstupu můžete vidět výsledek podle očekávání

Krok 5) „Funkce strftime“ umožňuje volat čas v libovolném formátu 24 hodin nebo 12 hodin.

Formátovat výstup data a času pomocí Strftime()

Pouhým definováním řídicího kódu, jako je %I/H pro hodinu, % M pro minutu, %S pro sekundu, lze volat čas pro různé formáty

12 hodin čas je deklarován [print now.strftime(“%I:%M:%S %p) ]

24 hodin čas je deklarován [print now.strftime(“%H:%M”)]

Zde je kompletní kód pro převod datetime na objekt String.

#
#Example file for formatting time and date output
#
from datetime import datetime
def main():
   #Times and dates can be formatted using a set of predefined string
   #Control codes
      now= datetime.now() #get the current date and time
      #%c - local date and time, %x-local's date, %X- local's time
      print(now.strftime("%c"))
      print(now.strftime("%x"))
      print(now.strftime("%X"))
##### Time Formatting ####
      #%I/%H - 12/24 Hour, %M - minute, %S - second, %p - local's AM/PM
      print(now.strftime("%I:%M:%S %p")) # 12-Hour:Minute:Second:AM
      print(now.strftime("%H:%M")) # 24-Hour:Minute

if __name__== "__main__":
    main()

V čem je Timedelta Python?

Časová delta v Python je objekt, který reprezentuje dobu trvání. Používá se hlavně k výpočtu doby trvání mezi dvěma daty a časy. Používá se také k načtení objektu s nějakou delta datem a časem. Objekt timedelta podporuje matematické operace, jako je sčítání, odčítánítracce, násobení, dělení atd.

Jak používat objekty Timedelta

S Python objektů timedelta, můžete odhadnout čas pro budoucnost i minulost. Jinými slovy, je to časový úsek pro předpovídání jakéhokoli zvláštního dne, data nebo času.

Pamatujte, že tato funkce neslouží k vytištění času nebo data, ale k VÝPOČTU o budoucnosti nebo minulosti. Let’s see a Python příklad timedelta, abyste to lépe pochopili.

Krok 1) Chcete-li spustit Timedelta Objects, musíte nejprve deklarovat příkaz import a poté spustit kód

  1. Napište příkaz importu pro timedelta
  2. Nyní napište kód pro tisk objektu z časové delty, jak je znázorněno na snímku obrazovky
  3. Spusťte kód. Časová delta představuje rozpětí 365 dní, 8 hodin a 15 minut a tiskne se stejně

Objekty Timedelta

Matoucí? Další krok pomůže -

Krok 2) Pojďme zjistit dnešní datum a čas, abychom zkontrolovali, zda naše prohlášení o importu funguje dobře. Když je kód spuštěn, vytiskne dnešní datum, což znamená, že náš příkaz k importu funguje dobře

Objekty Timedelta

Krok 3) Uvidíme, jak můžeme od nynějška získat datum za rok prostřednictvím objektů delta. Když spustíme kód, dává výstup podle očekávání.

Objekty Timedelta

Krok 4) Další příklad, jak lze časový rozdíl použít k výpočtu budoucího data z aktuálního data a času

Objekty Timedelta

Krok 5) Podívejme se na složitější příklad. Chtěl bych zjistit, kolik dní po Novém roce. Zde je návod, jak budeme postupovat

  • Pomocí today= date.today() získáme dnešní datum
  • Víme, že nový rok je vždy 1. ledna, ale rok může být jiný. Pomocí nyd= date(dnes.rok,1,1) uložíme nový rok do proměnné nyd
  • if nyd < today: compares whether the current date is greater than the new year. If yes, it enters the while loop
  • ((today-nyd).days) udává rozdíl mezi aktuálním datem a novým rokem ve DAYS

Objekty Timedelta

Výstup ukazuje, že „Nový rok již uplynul před 11 dny“.

Zde je kompletní pracovní kód

#
# Example file for working with timedelta objects
#
from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta

# construct a basic timedelta and print it
print (timedelta(days=365, hours=8, minutes=15))
# print today's date
print ("today is: " + str(datetime.now()))
# print today's date one year from now
print ("one year from now it will be:" + str(datetime.now() + timedelta(days=365)))
# create a timedelta that uses more than one argument
# print (in one week and 4 days it will be " + str(datetime.now() + timedelta(weeks=1, days=4)))
# How many days until New Year's Day?
today = date.today()  # get todays date
nyd = date(today.year, 1, 1)  # get New Year Day for the same year
# use date comparison to see if New Year Day has already gone for this year
# if it has, use the replace() function to get the date for next year
if nyd < today:
    print ("New Year day is already went by %d days ago" % ((today - nyd).days))

Python 2 Příklad

The following examples show the same date and time operations written for Python 2, where print is a statement rather than a function. Use these versions only when maintaining legacy Python 2 code.

from datetime import date
from datetime import time
from datetime import datetime
def main():
 	##DATETIME OBJECTS
    #Get today's date from datetime class
	today=datetime.now()
	#print today
	# Get the current time
	#t = datetime.time(datetime.now())
	#print "The current time is", t
	#weekday returns 0 (monday) through 6 (sunday)
        wd = date.weekday(today)
	#Days start at 0 for monday
        days= ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
        print "Today is day number %d" % wd
        print "which is a " + days[wd]

if __name__== "__main__":
    main()
#
#Example file for formatting time and date output
#
from datetime import datetime
def main():
   #Times and dates can be formatted using a set of predefined string
   #Control codes
      now= datetime.now() #get the current date and time
      #%c - local date and time, %x-local's date, %X- local's time
      print now.strftime("%c")
      print now.strftime("%x")
      print now.strftime("%X")
##### Time Formatting ####   
      #%I/%H - 12/24 Hour, %M - minute, %S - second, %p - local's AM/PM
      print now.strftime("%I:%M:%S %p") # 12-Hour:Minute:Second:AM
      print now.strftime("%H:%M") # 24-Hour:Minute   

if __name__== "__main__":
    main()
#
# Example file for working with timedelta objects
#
from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta

# construct a basic timedelta and print it
print timedelta(days=365, hours=8, minutes=15)
# print today's date
print "today is: " + str(datetime.now())
# print today's date one year from now
print "one year from now it will be:" + str(datetime.now() + timedelta(days=365))
# create a timedelta that uses more than one argument
# print "in one week and 4 days it will be " + str(datetime.now() + timedelta(weeks=1, days=4))
# How many days until New Year's Day?
today = date.today()  # get todays date
nyd = date(today.year, 1, 1)  # get New Year Day for the same year
# use date comparison to see if New Year Day has already gone for this year
# if it has, use the replace() function to get the date for next year
if nyd < today:
    print "New Year day is already went by %d days ago" % ((today - nyd).days)

Nejčastější dotazy

Use datetime.strptime(text, format) to parse a string into a datetime object. Pass the same directives strftime() uses, so “2018-06-29” reads with “%Y-%m-%d”. As the reverse of strftime(), strptime() turns human-readable text back into a datetime you can compute with.

A datetime without tzinfo is naive; attaching a time zone makes it aware. Use the built-in zoneinfo module (Python 3.9+) or the pytz package to localize datetimes, then convert between zones so calculations stay correct across regions.

Call the timestamp() method on a datetime to get the seconds since the Unix epoch as a float, for example datetime.now().timestamp(). To go the other way, datetime.fromtimestamp(value) rebuilds a datetime from a Unix timestamp.

Both return the current local date and time, but datetime.now() accepts an optional time zone argument, while datetime.today() does not. For time-zone-aware code, prefer datetime.now(tz) so the result carries the correct offset instead of staying naive.

Yes. The datetime module ships with Python, so no pip install is needed. Import it with “from datetime import datetime, date, time, timedelta” and the date, time, datetime, timedelta, and tzinfo classes become available immediately.

Call the isoformat() method to get a standard ISO 8601 string such as “2018-06-29T08:15:27”. For a date object it returns “YYYY-MM-DD”. isoformat() needs no control codes, unlike strftime(), which builds custom layouts from directives.

Machine learning pipelines turn raw timestamps into features such as weekday, hour, month, and elapsed time using datetime and timedelta. These engineered date features help time-series models and AI forecasting systems detect seasonal and cyclical patterns.

Yes. GitHub Copilot and agentic AI assistants generate strftime() format strings, timedelta arithmetic, and timezone conversions from a short comment, and can explain cryptic directives. Always run the suggested code, since date handling and offsets are easy to get wrong.

Shrňte tento příspěvek takto: