Table of Contents
This guide covers datetime in python with practical context and easy-to-follow details. Use it to understand the subject and apply the information confidently.
Python has the Datetime mudule To work and handles the same date and time. Let's try out some simple programs before we dig deeper.
Example 1: Returns the current date and time
import datetimedatetime_object = datetime.datetime.now()print(datetime_object)
When you run the program, the output will be in the form of:
2019-03-06 11:13:33.969330
In this example, we have just entered the Datetime module Using the Import datetime Statement.
The datetime class Is declared in the Datetime module , then use the Now () Command to create a Datetime Object containing the current local date and time.
Example 2: Returns the current date
import datetimedate_object = datetime.date.today()print(date_object)
When you run the program, the output will be in the form of:
2019-03-06
In this program, we use Today () Command which is declared in the Date class To get the current local date result.
You can use the Dir () Function to display a list of all properties of the Datetime module .
import datetimeprint(dir(datetime))
Run the program, the result is:
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__','__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo']
The classes commonly used in the Datetime module Are:
- Class date
- Class time
- Datetime class
- Class timedelta
The object of the Date class Returns the DateInformation (date), not the time information. The date is transmitted as 'year, month, day'.
import datetimed = datetime.date(2019, 4, 12)print(d)
When you run the program, the output will be in the form of:
2019-04-12
You can also update the Date class From the Datetime module Like this:
from datetime import datea = date(2019, 4, 12)print(a)
Example 3: Update the current date
Using Today () method
from datetime import datetoday = date.today()print("Ngay hien tai la:", today)
Example 4: Call the date from the timestamp
Unix Time (Unix timestamp) is a system for expressing a point on the time axis, according to the time axis it uses the number of seconds to determine the time, with the original point from 00: 00: 00 on January 1 / 1970 UTC hour.
For example at 00: 00: 00 - 12/02/2016 the timestamp value is 1455235200; It means that from 00: 00 to 1/1/1970 to 00: 00: 00 - 12/02/2016 is 1455235200 seconds.
And in Python, you can create date objects from a Timestamp.
from datetime import datetimestamp = date.fromtimestamp(1551916800)print("Date =", timestamp)
When you run the program, the output will be in the form of:
Date = 2019-03-07
Example 5: Print the current date
from datetime import date# viết bởi TipsMake.comtoday = date.today()print("Nam hien tai:", today.year)print("Thang hien tai:", today.month)print("Ngay hien tai:", today.day)
When you run the program, the output will be in the form of:
Nam hien tai: 2019Thang hien tai: 3Ngay hien tai: 7
The object of Class time Returns the current time information, not including date information.
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)# viet boi TipsMake.comc = time(hour = 11, minute = 34, second = 56)print("c =", c)# time(hour, minute, second, microsecond)d = time(11, 34, 56, 234566)print("d =", d)
The result is:
a = 00:00:00b = 11:34:56c = 11:34:56d = 11:34:56.234566
Example 6: Print hours, minutes, seconds and microseconds
from datetime import timea = time(11, 34, 56)print("hour =", a.hour)print("minute =", a.minute)print("second =", a.second)print("microsecond =", a.microsecond)
When you run the program, the output will be in the form of:
hour = 11minute = 34second = 56microsecond = 0
In the above example we do not pass parameters for microseconds so the return value is in the default form of 0.
The object of the Datetime class Returns results that include Both time and date information .
from datetime import datetime#datetime được truyền ở dạng 'year, month, day'.a = datetime(2019, 3, 7)print(a)# datetime được truyền ở dạng 'year, month, day, hour, minute, second, microsecond'b = datetime(2019, 3, 7, 23, 55, 59, 342380)print(b)
Running the program is the result:
2019-03-07 00:00:002019-03-07 23:55:59.342380
The first 3 parameters 'year, month, day' are required.
Example 7: Print the year, month, hour, minute, timestamp
from datetime import datetimea = datetime(2019, 3, 7, 23, 55, 59, 342380)print("year =", a.year)print("month =", a.month)print("hour =", a.hour)print("minute =", a.minute)print("timestamp =", a.timestamp())
The result is:
year = 2019month = 3hour = 23minute = 55timestamp = 1551977759.34238
Timedelta Is a Time period that describes the difference between two timelines .
from datetime import datetime, date# khoảng thời gian chênh lệch giữa 2 ngày thángt1 = date(year = 2018, month = 7, day = 12)t2 = date(year = 2017, month = 12, day = 23)t3 = t1 - t2print("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 - t5print("t6 =", t6)
The result is:
t3 = 201 days, 0:00:00t6 = -333 days, 1:14:20
T3 and t6 Here are Timedelta Objects
Example 8: Time difference between two timedelta objects
from datetime import timedeltat1 = timedelta(weeks = 2, days = 5, hours = 1, seconds = 33)t2 = timedelta(days = 4, hours = 11, minutes = 4, seconds = 54)t3 = t1 - t2print("t3 =", t3)
Running the program, we get the following output:
t3 = 14 days, 13:55:39
Example 9: Handling timedelta with negative value
from datetime import timedeltat1 = timedelta(seconds = 33)t2 = timedelta(seconds = 54)t3 = t1 - t2print("t3 =", t3)print("t3 =", abs(t3))
The results are:
t3 = -1 day, 23:59:39t3 = 0:00:21
Example 10: Convert the timedelta difference time to the total number of seconds
You can convert the result to the total number of seconds using Total_seconds () method.
from datetime import timedeltat = timedelta(days = 5, hours = 1, seconds = 33, microseconds = 233423)print("tong so giay =", t.total_seconds())
We get the result:
Tong so giay = 435633.233423
Operators support timedelta:
- T1 = t2 + t3 T2 = (hours = 8, seconds = 12) T3 = (hours = 2, minutes = 3) >>> t1 = (hours = 10, minutes = 3, seconds = 12)
- T1 = t2 - t3 T2 = (hours = 12, seconds = 2) T3 = (hours = 1, minutes = 4) >>> t1 = (hours = 11, minutes = 56, seconds = 2)
- T1 = t2 * i T1 = i * t2 T2 = (hours = 10, seconds = 2) I = 3 >>> t1 = (days = 1, hours = 6, seconds = 6)
- T1 = t2 T2 = (hours = 25, seconds = 2) >>> t1 = (days: 1, hours: 1, seconds: 2)
- + t1 Returns t1
- -t1 T1 = (hours = 10, seconds = 2) >>> -t1 = (days = -1, hours = 13, minutes = 59, seconds = 58)
- Abs (t) : Absolute value, equivalent to + t when t. Days> = 0, and is -t when t. Days >> t = (days = -2, hours = 23, minutes = 3) >>> abs (t) = (days = 1, hours = 0, minutes = 57)
- Str (t) : Returns the string according to the form [D day [s], ] [H] H: MM: SS [. UUUUUU], D can receive negative values.
- Repr (t) : Returns the string according to the form datetime. Timedelta (D [, S [, U]]), D can receive negative values
Dates and times are used in different forms, the US uses Mm / dd / yyyy Format, while Dd / mm / yyyy is More common in the UK.
Python has Strftime () And Strptime () Methods to handle this.
Example 11: Date format using strftime ()
from datetime import datetime# ngày giờ hiện tạinow = datetime.now()t = now.strftime("%H:%M:%S")print("time:", t)s1 = now.strftime("%m/%d/%Y, %H:%M:%S")# định dạng mm/dd/YY H:M:Sprint("s1:", s1)s2 = now.strftime("%d/%m/%Y, %H:%M:%S")# định dạng dd/mm/YY H:M:Sprint("s2:", s2)
The program returns the result:
time: 04:34:52s1: 03/07/2019, 04:34:52s2: 07/03/2019, 04:34:52
Here % Y, % m, % d, % H . Are format parameters. The Strftime () Method is used to return a string formatted based on those parameters.
Parameter scope:
- % 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 - month [00, 01, ., 58, 59]
- % S - second [00, 01, ., 58, 59]
from datetime import datetimedate_string = "7 March, 2019"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 result is:
date_string = 7 March, 2019date_object = 2019-03-07 00:00:00
Suppose, you are working on a project and need to display the date and time based on the time zone you need. Instead of trying to search and search for the time zone yourself, you should use the Module pytZ As follows:
from datetime import datetimeimport pytzlocal = 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"))
Run the program, the result is:
Local time: 2019-03-07 13:10:44.260462America/New_York time: 2019-03-07 13:10:44.260462Europe/London time: 2019-03-07 13:10:44.260462
In this example, Datetime_NY And Datetime_London Are Datetime Objects that contain the current date and time of the corresponding time zone.
FAQ
What should I check before following these steps?
Confirm device and software compatibility, save important data, and make sure you have the required permissions, files, and account access.
Why might the process not work?
Common causes include outdated software, missing permissions, incompatible hardware, an unstable connection, or completing a step in the wrong order.
Can I undo the changes if necessary?
That depends on the tool or setting. Use built-in restore options when available, keep a backup, and record the original configuration first.
Reader Comments 0
Sign in with email or Google to join the discussion.