Python datetime (mit Beispielen)

In diesem Artikel lernen Sie anhand von Beispielen, wie Sie Datum und Uhrzeit in Python bearbeiten.

Python hat ein Modul namens datetime , um mit Datum und Uhrzeit zu arbeiten. Lassen Sie uns ein paar einfache Programme erstellen, die sich auf Datum und Uhrzeit beziehen, bevor wir tiefer gehen.

Beispiel 1: Aktuelles Datum und Uhrzeit abrufen

 import datetime datetime_object = datetime.datetime.now() print(datetime_object) 

Wenn Sie das Programm ausführen, lautet die Ausgabe wie folgt:

 2018-12-19 09: 26: 03.478039

Hier haben wir das datetime- Modul mithilfe der import datetimeAnweisung importiert .

Eine der im datetimeModul definierten Klassen ist datetimeclass. Anschließend haben wir mit der now()Methode ein datetimeObjekt erstellt, das das aktuelle lokale Datum und die aktuelle Uhrzeit enthält.

Beispiel 2: Aktuelles Datum abrufen

  import datetime date_object = datetime.date.today() print(date_object) 

Wenn Sie das Programm ausführen, lautet die Ausgabe wie folgt:

 2018-12-19

In diesem Programm haben wir die today()in der dateKlasse definierte Methode verwendet , um ein dateObjekt mit dem aktuellen lokalen Datum abzurufen.

Was ist in datetime?

Wir können die Funktion dir () verwenden, um eine Liste mit allen Attributen eines Moduls abzurufen.

 import datetime print(dir(datetime))

Wenn Sie das Programm ausführen, lautet die Ausgabe wie folgt:

 ('MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_divide_and_round', 'date', ' datetime ',' datetime_CAPI ',' time ',' timedelta ',' timezone ',' tzinfo ') 

Häufig verwendete Klassen im datetime-Modul sind:

  • Datum Klasse
  • Zeitklasse
  • datetime Klasse
  • Zeitdelta-Klasse

datetime.date Klasse

Sie können dateObjekte aus der dateKlasse instanziieren . Ein Datumsobjekt repräsentiert ein Datum (Jahr, Monat und Tag).

Beispiel 3: Datumsobjekt zur Darstellung eines Datums

  import datetime d = datetime.date(2019, 4, 13) print(d) 

Wenn Sie das Programm ausführen, lautet die Ausgabe wie folgt:

 2019-04-13

Wenn Sie sich fragen, ist date()im obigen Beispiel ein Konstruktor der dateKlasse. Der Konstruktor verwendet drei Argumente: Jahr, Monat und Tag.

Die Variable a ist ein dateObjekt.

Wir können nur dateKlassen aus dem datetimeModul importieren . Hier ist wie:

  from datetime import date a = date(2019, 4, 13) print(a)

Beispiel 4: Aktuelles Datum abrufen

Sie können ein dateObjekt mit dem aktuellen Datum mithilfe einer Klassenmethode mit dem Namen erstellen today(). Hier ist wie:

  from datetime import date today = date.today() print("Current date =", today) 

Beispiel 5: Datum aus einem Zeitstempel abrufen

Wir können auch dateObjekte aus einem Zeitstempel erstellen . Ein Unix-Zeitstempel ist die Anzahl der Sekunden zwischen einem bestimmten Datum und dem 1. Januar 1970 bei UTC. Sie können einen Zeitstempel mithilfe der fromtimestamp()Methode in ein Datum konvertieren .

  from datetime import date timestamp = date.fromtimestamp(1326244364) print("Date =", timestamp) 

Wenn Sie das Programm ausführen, lautet die Ausgabe wie folgt:

 Datum = 2012-01-11

Beispiel 6: Drucken Sie das heutige Jahr, den Monat und den Tag

Wir können Jahr, Monat, Tag, Wochentag usw. leicht aus dem Datumsobjekt abrufen. Hier ist wie:

  from datetime import date # date object of today's date today = date.today() print("Current year:", today.year) print("Current month:", today.month) print("Current day:", today.day) 

datetime.time

Ein aus der timeKlasse instanziiertes Zeitobjekt repräsentiert die Ortszeit.

Beispiel 7: Zeitobjekt zur Darstellung der Zeit

  from datetime import time # time(hour = 0, minute = 0, second = 0) a = time() print("a =", a) # time(hour, minute and second) b = time(11, 34, 56) print("b =", b) # time(hour, minute and second) c = time(hour = 11, minute = 34, second = 56) print("c =", c) # time(hour, minute, second, microsecond) d = time(11, 34, 56, 234566) print("d =", d) 

Wenn Sie das Programm ausführen, lautet die Ausgabe wie folgt:

 a = 00:00:00 b = 11:34:56 c = 11:34:56 d = 11: 34: 56.234566 

Beispiel 8: Drucken Sie Stunde, Minute, Sekunde und Mikrosekunde

Sobald Sie ein timeObjekt erstellt haben, können Sie seine Attribute wie Stunde, Minute usw. einfach drucken.

  from datetime import time a = time(11, 34, 56) print("hour =", a.hour) print("minute =", a.minute) print("second =", a.second) print("microsecond =", a.microsecond) 

Wenn Sie das Beispiel ausführen, lautet die Ausgabe wie folgt:

 Stunde = 11 Minuten = 34 Sekunden = 56 Mikrosekunden = 0 

Beachten Sie, dass wir kein Mikrosekundenargument übergeben haben. Daher wird der Standardwert 0gedruckt.

datetime.datetime

The datetime module has a class named dateclass that can contain information from both date and time objects.

Example 9: Python datetime object

  from datetime import datetime #datetime(year, month, day) a = datetime(2018, 11, 28) print(a) # datetime(year, month, day, hour, minute, second, microsecond) b = datetime(2017, 11, 28, 23, 55, 59, 342380) print(b) 

When you run the program, the output will be:

 2018-11-28 00:00:00 2017-11-28 23:55:59.342380 

The first three arguments year, month and day in the datetime() constructor are mandatory.

Example 10: Print year, month, hour, minute and timestamp

  from datetime import datetime a = datetime(2017, 11, 28, 23, 55, 59, 342380) print("year =", a.year) print("month =", a.month) print("hour =", a.hour) print("minute =", a.minute) print("timestamp =", a.timestamp()) 

When you run the program, the output will be:

 year = 2017 month = 11 day = 28 hour = 23 minute = 55 timestamp = 1511913359.34238 

datetime.timedelta

A timedelta object represents the difference between two dates or times.

Example 11: Difference between two dates and times

  from datetime import datetime, date t1 = date(year = 2018, month = 7, day = 12) t2 = date(year = 2017, month = 12, day = 23) t3 = t1 - t2 print("t3 =", t3) t4 = datetime(year = 2018, month = 7, day = 12, hour = 7, minute = 9, second = 33) t5 = datetime(year = 2019, month = 6, day = 10, hour = 5, minute = 55, second = 13) t6 = t4 - t5 print("t6 =", t6) print("type of t3 =", type(t3)) print("type of t6 =", type(t6)) 

When you run the program, the output will be:

 t3 = 201 days, 0:00:00 t6 = -333 days, 1:14:20 type of t3 = type of t6 = 

Notice, both t3 and t6 are of type.

Example 12: Difference between two timedelta objects

  from datetime import timedelta t1 = timedelta(weeks = 2, days = 5, hours = 1, seconds = 33) t2 = timedelta(days = 4, hours = 11, minutes = 4, seconds = 54) t3 = t1 - t2 print("t3 =", t3) 

When you run the program, the output will be:

 t3 = 14 days, 13:55:39 

Here, we have created two timedelta objects t1 and t2, and their difference is printed on the screen.

Example 13: Printing negative timedelta object

  from datetime import timedelta t1 = timedelta(seconds = 33) t2 = timedelta(seconds = 54) t3 = t1 - t2 print("t3 =", t3) print("t3 =", abs(t3)) 

When you run the program, the output will be:

 t3 = -1 day, 23:59:39 t3 = 0:00:21 

Example 14: Time duration in seconds

You can get the total number of seconds in a timedelta object using total_seconds() method.

  from datetime import timedelta t = timedelta(days = 5, hours = 1, seconds = 33, microseconds = 233423) print("total seconds =", t.total_seconds()) 

When you run the program, the output will be:

 total seconds = 435633.233423 

You can also find sum of two dates and times using + operator. Also, you can multiply and divide a timedelta object by integers and floats.

Python format datetime

The way date and time is represented may be different in different places, organizations etc. It's more common to use mm/dd/yyyy in the US, whereas dd/mm/yyyy is more common in the UK.

Python has strftime() and strptime() methods to handle this.

Python strftime() - datetime object to string

The strftime() method is defined under classes date, datetime and time. The method creates a formatted string from a given date, datetime or time object.

Example 15: Format date using strftime()

  from datetime import datetime # current date and time now = datetime.now() t = now.strftime("%H:%M:%S") print("time:", t) s1 = now.strftime("%m/%d/%Y, %H:%M:%S") # mm/dd/YY H:M:S format print("s1:", s1) s2 = now.strftime("%d/%m/%Y, %H:%M:%S") # dd/mm/YY H:M:S format print("s2:", s2) 

When you run the program, the output will be something like:

 time: 04:34:52 s1: 12/26/2018, 04:34:52 s2: 26/12/2018, 04:34:52 

Here, %Y, %m, %d, %H etc. are format codes. The strftime() method takes one or more format codes and returns a formatted string based on it.

In the above program, t, s1 and s2 are strings.

  • %Y - year (0001,… , 2018, 2019,… , 9999)
  • %m - month (01, 02,… , 11, 12)
  • %d - day (01, 02,… , 30, 31)
  • %H - hour (00, 01,… , 22, 23
  • %M - minute (00, 01,… , 58, 59)
  • %S - second (00, 01,… , 58, 59)

To learn more about strftime() and format codes, visit: Python strftime().

Python strptime() - string to datetime

The strptime() method creates a datetime object from a given string (representing date and time).

Example 16: strptime()

  from datetime import datetime date_string = "21 June, 2018" print("date_string =", date_string) date_object = datetime.strptime(date_string, "%d %B, %Y") print("date_object =", date_object) 

When you run the program, the output will be:

 date_string = 21 June, 2018 date_object = 2018-06-21 00:00:00 

The strptime() method takes two arguments:

  1. eine Zeichenfolge, die Datum und Uhrzeit darstellt
  2. Formatcode, der dem ersten Argument entspricht

By the way, %d, %Bund %YFormatcodes werden für Tag, Monat (vollständiger Name) und Jahr verwendet wurden .

Besuchen Sie Python strptime (), um mehr zu erfahren.

Zeitzone in Python behandeln

Angenommen, Sie arbeiten an einem Projekt und müssen Datum und Uhrzeit basierend auf ihrer Zeitzone anzeigen. Anstatt zu versuchen, die Zeitzone selbst zu verwalten, empfehlen wir Ihnen, ein pytZ-Modul eines Drittanbieters zu verwenden.

  from datetime import datetime import pytz local = datetime.now() print("Local:", local.strftime("%m/%d/%Y, %H:%M:%S")) tz_NY = pytz.timezone('America/New_York') datetime_NY = datetime.now(tz_NY) print("NY:", datetime_NY.strftime("%m/%d/%Y, %H:%M:%S")) tz_London = pytz.timezone('Europe/London') datetime_London = datetime.now(tz_London) print("London:", datetime_London.strftime("%m/%d/%Y, %H:%M:%S")) 

Wenn Sie das Programm ausführen, lautet die Ausgabe wie folgt:

 Ortszeit: 2018-12-20 13: 10: 44.260462 America / New_York Zeit: 2018-12-20 13: 10: 44.260462 Europa / London Zeit: 2018-12-20 13: 10: 44.260462 

Hier sind datetime_NY und datetime_London datetime-Objekte, die das aktuelle Datum und die aktuelle Uhrzeit ihrer jeweiligen Zeitzone enthalten.

Interessante Beiträge...