Python Datum i vrijeme, vrijemeDelta, Strftime(Format) s primjerima

โšก Pametni saลพetak

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.
  • โœ… Oblikovanje: 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 subtraction.
  • ๐Ÿ› ๏ธ Direktive: The same control codes drive strftime() for output and strptime() for reading a string back into a datetime.
  • ๐Ÿค– Tijekovi rada umjetne inteligencije: Machine learning pipelines derive datetime features such as weekday and hour for time-series models.

Python Datum vrijeme

In Python, datum, vrijeme i datumvrijeme 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.

Datum i vrijeme ulazi u Python are categorized into 5 main classes.

  • datum โ€“ manipulirajte samo datumom (mjesec, dan, godina)
  • vrijeme โ€“ vrijeme neovisno o danu (sat, minuta, sekunda, mikrosekunda)
  • datetime โ€“ kombinacija vremena i datuma (mjesec, dan, godina, sat, sekunda, mikrosekunda)
  • timedeltaโ€” trajanje vremena koje se koristi za manipuliranje datumima
  • tzinfoโ€” Abstract klasa za rad s vremenskim zonama

Kako koristiti klasu datuma i vremena

Korak 1) Prije pokretanja koda za format datuma i vremena u Python, vaลพno je da uvezete Python module datuma i vremena kao ลกto je prikazano na slici ispod.

Koristite klasu datuma i vremena

Ovi uvozni iskazi unaprijed su definirani dijelovi funkcionalnosti u Python library that let you manipulate dates and times, without writing any code.

Razmotrite sljedeฤ‡e toฤke prije izvoฤ‘enja Python kod formata datuma i vremena

from datetime import date

Ovaj redak govori o Python tumaฤ za uvoz klase datuma iz modula datetime Python. We are not writing the code for this date functionality but are simply importing it for our use.

Ispiลกi datum pomoฤ‡u date.today()

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

Pogledajmo primjer

Ispiลกi datum pomoฤ‡u date.today()

Danaลกnji broj za radni dan

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.

Dan Broj dana u tjednu
Monday 0
Utorak 1
Srijeda 2
ฤŒetvrtak 3
Petak 4
Subota 5
nedjelja 6

Broj dana u tjednu koristan je za nizove ฤiji indeks ovisi o danu u tjednu.

Ispiลกi datum pomoฤ‡u date.today()

Korak 2) Zatim stvaramo instancu objekta datuma.

Koristite klasu datuma i vremena

Korak 3) Zatim ispisujemo datum i pokreฤ‡emo kod.

Koristite klasu datuma i vremena

The output is as expected.

Python Trenutaฤni datum i vrijeme: sada() danas()

Korak 1) Kao objekti datuma, takoฤ‘er moลพemo koristiti โ€œOBJEKTI DATUM-VRIJEMEโ€ in Python. Python objekti datuma i vremena daju datum zajedno s vremenom sati, minute, sekunde i milisekunde.

Python Trenutni datum i vrijeme

Kada izvrลกimo kod za datum i vrijeme, on daje izlaz s trenutnim datumom i vremenom.

Korak 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())
  • Uvezli smo vremensku klasu. Dodijelit ฤ‡emo mu trenutnu vrijednost vremena koristeฤ‡i datetime.now()
  • Varijabli t pridruลพujemo vrijednost trenutnog vremena.

A ovo ฤ‡e mi dati dovoljno vremena. Pa pokrenimo ovaj program.

Python Trenutni datum i vrijeme

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.

Korak 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).
  • Koristite tu vrijednost indeksa da znate koji je dan. U naลกem sluฤaju, to je #2 i predstavlja srijedu, tako da ฤ‡e u izlazu ispisati "Koja je srijeda."

Python Trenutni datum i vrijeme

Ovdje je kompletan kod za dobivanje trenutnog datuma i vremena koristeฤ‡i datetime sada

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()

Kako formatirati izlaz datuma i vremena pomoฤ‡u Strftime()

So far, we have learned how to use datetime and date objekt u Python. Napravit ฤ‡emo korak dalje i nauฤiti kako koristiti funkciju oblikovanja za formatiranje vremena i datuma.

Korak 1) Prvo ฤ‡emo vidjeti jednostavan korak kako formatirati godinu. Bolje je razumjeti na primjeru.

Formatirajte izlaz datuma i vremena pomoฤ‡u Strftime()

  • Koristili smo โ€œstrftime functionโ€ za oblikovanje.
  • Ova funkcija koristi razliฤite kontrolni kod dati izlaz.
  • Each control code resembles different parameters like year, month, weekday and date [(%y/%Y โ€“ godina), (%a/%A- radni dan), (%b/%B- mjesec), (%d โ€“ dan u mjesecu)] .
  • U naลกem sluฤaju jest ("%Y") koji nalikuje godini, ispisuje punu godinu sa stoljeฤ‡em (npr. 2018.).

Korak 2) Sada ako zamijenite (โ€œ%Yโ€) malim slovima, tj. ( โ€œ%y) i izvrลกite kod, izlaz ฤ‡e prikazati samo (18), a ne (2018). Stoljeฤ‡e u godini neฤ‡e se prikazati kao ลกto je prikazano na slici ispod

Formatirajte izlaz datuma i vremena pomoฤ‡u Strftime()

Korak 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.

Formatirajte izlaz datuma i vremena pomoฤ‡u 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โ€.

Formatirajte izlaz datuma i vremena pomoฤ‡u Strftime()

Korak 4) Uz pomoฤ‡ funkcije โ€œStrftimeโ€ takoฤ‘er moลพemo dohvatiti lokalno vrijeme sustava, datum ili oboje.

  1. %C- oznaฤava lokalni datum i vrijeme
  2. %x- oznaฤava lokalni datum
  3. %X- oznaฤava lokalno vrijeme

Formatirajte izlaz datuma i vremena pomoฤ‡u Strftime()

U izlazu moลพete vidjeti oฤekivani rezultat

Korak 5) Funkcija "strftime" omoguฤ‡uje vam da pozovete vrijeme u bilo kojem formatu 24 sata ili 12 sati.

Formatirajte izlaz datuma i vremena pomoฤ‡u Strftime()

Samo definiranjem kontrolnog koda kao ลกto je %I/H za sat, % M za minutu, %S za sekundu, moลพe se pozvati vrijeme za razliฤite formate

12 sati vrijeme je deklarirano [print now.strftime(โ€œ%I:%M:%S %p) ]

24 sati vrijeme je deklarirano [print now.strftime(โ€œ%H:%Mโ€)]

Ovdje je potpuni kod za pretvaranje datuma i vremena u String objekt.

#
#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()

U ฤemu je Timedelta Python?

Timedelta in Python je objekt koji predstavlja trajanje. Uglavnom se koristi za izraฤunavanje trajanja izmeฤ‘u dva datuma i vremena. Takoฤ‘er se koristi za dohvaฤ‡anje objekta s nekim delta datumom i vremenom. Objekt timedelta podrลพava matematiฤke operacije poput zbrajanja, podraฤunavanjatraccije, mnoลพenje, dijeljenje itd.

Kako koristiti Timedelta objekte

Kontakt Python timedelta objekata, moลพete procijeniti vrijeme i za buduฤ‡nost i za proลกlost. Drugim rijeฤima, to je vremenski raspon za predviฤ‘anje bilo kojeg posebnog dana, datuma ili vremena.

Imajte na umu da ova funkcija nije za ispis vremena ili datuma, veฤ‡ za neลกto za IZRAฤŒUNANJE buduฤ‡nosti ili proลกlosti. Letโ€™s see a Python timedelta primjer za bolje razumijevanje.

Korak 1) Da biste pokrenuli Timedelta Objects, morate prvo deklarirati import naredbu, a zatim izvrลกiti kod

  1. Napiลกite izjavu uvoza za timedelta
  2. Sada napiลกite kod za ispis objekta iz vremenske delte kao ลกto je prikazano na snimci zaslona
  3. Pokrenite kod. Timedelta predstavlja raspon od 365 dana, 8 sati i 15 minuta i ispisuje isto

Timedelta objekti

Zbunjujuฤ‡e? Sljedeฤ‡i korak ฤ‡e pomoฤ‡i -

Korak 2) Uzmimo danaลกnji datum i vrijeme da provjerimo funkcionira li naลกa izjava o uvozu dobro. Kada se kรดd izvrลกi, on ispisuje danaลกnji datum ลกto znaฤi da naลกa izjava o uvozu radi dobro

Timedelta objekti

Korak 3) Vidjet ฤ‡emo kako moลพemo dohvatiti datum za godinu dana kroz delta objekte. Kada pokrenemo kod, on daje oฤekivani izlaz.

Timedelta objekti

Korak 4) Joลก jedan primjer kako se delta vremena moลพe koristiti za izraฤunavanje buduฤ‡eg datuma iz trenutnog datuma i vremena

Timedelta objekti

Korak 5) Pogledajmo sloลพeniji primjer. ลฝelio bih odrediti koliko dana je proลกlo od Nove godine. Evo kako ฤ‡emo nastaviti

  • Koriลกtenjem today= date.today() dobit ฤ‡emo danaลกnji datum
  • Znamo da je nova godina uvijek 1. sijeฤnja, ali godina bi mogla biti drugaฤija. Koristeฤ‡i nyd= date(today.year,1,1) spremamo novu godinu u varijablu 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) daje razliku izmeฤ‘u trenutnog datuma i nove godine u DANIMA

Timedelta objekti

Rezultat pokazuje da je "Nova godina veฤ‡ proลกla prije 11 dana."

Ovdje je kompletan radni kod

#
# 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 Primjer

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)

Pitanja i odgovori

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.

Saลพmite ovu objavu uz: