Cách kiểm tra định dạng ngày trong python

Có một số cách chúng ta có thể thực hiện để có được ngày hiện tại. Chúng tôi sẽ sử dụng lớp date của mô-đun datetime để hoàn thành nhiệm vụ này


ví dụ 1. Python lấy ngày hôm nay

from datetime import date

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

đầu ra

Today's date: 2022-12-27

Ở đây, chúng tôi đã nhập lớp date từ mô-đun datetime. Sau đó, chúng tôi đã sử dụng phương thức date.today() để lấy ngày địa phương hiện tại


ví dụ 2. Ngày hiện tại ở các định dạng khác nhau

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)

đầu ra

d1 = 27/12/2022
d2 = December 27, 2022
d3 = 12/27/22
d4 = Dec-27-2022

Nếu chúng ta cần lấy ngày và giờ hiện tại, bạn có thể sử dụng lớp datetime của mô-đun datetime

Trong bài học này, bạn sẽ học cách so sánh hai ngày hoặc ngày giờ trong Python

Bạn sẽ học cách

  • Kiểm tra xem một ngày nhất định lớn hơn hay nhỏ hơn một ngày khác
  • So sánh hai mốc thời gian
  • So sánh hai chuỗi ngày

Mục lục

Cách so sánh hai ngày trong Python

Use (like <, >, <=, >=, !=, etc.) to compare dates in Python. Let’s see the steps to compare dates with the help of the datetime module.

  1. nhập mô-đun ngày giờ

    Mô-đun datetime trong Python cung cấp nhiều chức năng khác nhau để tạo và thao tác ngày và giờ. Sử dụng câu lệnh 

    Date1: 2022-09-13 00:00:00
    Date2: 2022-10-07 15:12:52.970943
    Date1 is lower than date2
    
    Date1: 2022-09-13 00:00:00
    Date2: 2021-11-23 00:00:00
    Date1 is greater than date2
    0 để nhập lớp 
    Date1: 2022-09-13 00:00:00
    Date2: 2022-10-07 15:12:52.970943
    Date1 is lower than date2
    
    Date1: 2022-09-13 00:00:00
    Date2: 2021-11-23 00:00:00
    Date1 is greater than date2
    1 từ mô-đun ngày giờ

  2. Chuyển đổi chuỗi ngày thành đối tượng datetime

    Nếu ngày ở định dạng chuỗi, chúng ta cần chuyển đổi cả hai chuỗi ngày thành đối tượng ngày giờ trước khi so sánh chúng
    Sử dụng hàm 

    Date1: 2022-09-13 00:00:00
    Date2: 2022-10-07 15:12:52.970943
    Date1 is lower than date2
    
    Date1: 2022-09-13 00:00:00
    Date2: 2021-11-23 00:00:00
    Date1 is greater than date2
    2 để chuyển đổi chuỗi ngày thành đối tượng ngày giờ theo 
    Date1: 2022-09-13 00:00:00
    Date2: 2022-10-07 15:12:52.970943
    Date1 is lower than date2
    
    Date1: 2022-09-13 00:00:00
    Date2: 2021-11-23 00:00:00
    Date1 is greater than date2
    3 tương ứng. Ví dụ: mã định dạng 
    Date1: 2022-09-13 00:00:00
    Date2: 2022-10-07 15:12:52.970943
    Date1 is lower than date2
    
    Date1: 2022-09-13 00:00:00
    Date2: 2021-11-23 00:00:00
    Date1 is greater than date2
    4 dành cho 
    Date1: 2022-09-13 00:00:00
    Date2: 2022-10-07 15:12:52.970943
    Date1 is lower than date2
    
    Date1: 2022-09-13 00:00:00
    Date2: 2021-11-23 00:00:00
    Date1 is greater than date2
    5

  3. So sánh hai đối tượng datetime

    Sử dụng (như

    Date1: 2022-09-13 00:00:00
    Date2: 2022-10-07 15:12:52.970943
    Date1 is lower than date2
    
    Date1: 2022-09-13 00:00:00
    Date2: 2021-11-23 00:00:00
    Date1 is greater than date2
    6,
    Date1: 2022-09-13 00:00:00
    Date2: 2022-10-07 15:12:52.970943
    Date1 is lower than date2
    
    Date1: 2022-09-13 00:00:00
    Date2: 2021-11-23 00:00:00
    Date1 is greater than date2
    7,
    Date1: 2022-09-13 00:00:00
    Date2: 2022-10-07 15:12:52.970943
    Date1 is lower than date2
    
    Date1: 2022-09-13 00:00:00
    Date2: 2021-11-23 00:00:00
    Date1 is greater than date2
    8,
    Date1: 2022-09-13 00:00:00
    Date2: 2022-10-07 15:12:52.970943
    Date1 is lower than date2
    
    Date1: 2022-09-13 00:00:00
    Date2: 2021-11-23 00:00:00
    Date1 is greater than date2
    9,
    from datetime import datetime
    
    # input dates
    d1 = datetime(2022, 6, 27).date()
    d2 = datetime(2022, 6, 27).date()
    d3 = datetime(2021, 5, 14).date()
    d4 = datetime(2022, 10, 10).date()
    
    # omit .date() function if you want to compare the entire datetime object
    # use .date() id you want to compare only the date part of it
    
    # date equality check
    print('Date_1:', d1, 'Date_2:', d2, 'Date3:', d3)
    print('Date_1 and Date_2 are equal:', d1 == d2)
    print('Date_1 and Date_3 are equal:', d1 == d3)
    
    # check if date is greater than another date
    print('Date_1:', d1, 'Date_3:', d3, 'Date_4:', d4)
    print('date_1 is greater than date_3:', d1 > d3)
    print('date_1 is greater than date_4:', d1 > d4)
    
    # check if date is less than another date
    print('Date_1:', d1, 'Date_3:', d3, 'Date_4:', d4)
    print('date_1 is less than date_3:', d1 < d3)
    print('date_1 is less than date_4:', d1 < d4)
    
    # date not equal to check
    print('Date_1:', d1, 'Date_2:', d2, 'Date__3:', d3)
    print('Date_1 and Date_2 are NOT equal:', d1 != d2)
    print('Date_1 and Date_3 are NOT equal:', d1 != d3)
    0, v.v. ) để so sánh ngày trong Python. Ví dụ:
    from datetime import datetime
    
    # input dates
    d1 = datetime(2022, 6, 27).date()
    d2 = datetime(2022, 6, 27).date()
    d3 = datetime(2021, 5, 14).date()
    d4 = datetime(2022, 10, 10).date()
    
    # omit .date() function if you want to compare the entire datetime object
    # use .date() id you want to compare only the date part of it
    
    # date equality check
    print('Date_1:', d1, 'Date_2:', d2, 'Date3:', d3)
    print('Date_1 and Date_2 are equal:', d1 == d2)
    print('Date_1 and Date_3 are equal:', d1 == d3)
    
    # check if date is greater than another date
    print('Date_1:', d1, 'Date_3:', d3, 'Date_4:', d4)
    print('date_1 is greater than date_3:', d1 > d3)
    print('date_1 is greater than date_4:', d1 > d4)
    
    # check if date is less than another date
    print('Date_1:', d1, 'Date_3:', d3, 'Date_4:', d4)
    print('date_1 is less than date_3:', d1 < d3)
    print('date_1 is less than date_4:', d1 < d4)
    
    # date not equal to check
    print('Date_1:', d1, 'Date_2:', d2, 'Date__3:', d3)
    print('Date_1 and Date_2 are NOT equal:', d1 != d2)
    print('Date_1 and Date_3 are NOT equal:', d1 != d3)
    1 để kiểm tra xem datetime_1 có lớn hơn datetime_2 không

  4. So sánh hai ngày

    Nếu bạn chỉ muốn so sánh ngày tháng của đối tượng DateTime, hãy sử dụng phương thức

    from datetime import datetime
    
    # input dates
    d1 = datetime(2022, 6, 27).date()
    d2 = datetime(2022, 6, 27).date()
    d3 = datetime(2021, 5, 14).date()
    d4 = datetime(2022, 10, 10).date()
    
    # omit .date() function if you want to compare the entire datetime object
    # use .date() id you want to compare only the date part of it
    
    # date equality check
    print('Date_1:', d1, 'Date_2:', d2, 'Date3:', d3)
    print('Date_1 and Date_2 are equal:', d1 == d2)
    print('Date_1 and Date_3 are equal:', d1 == d3)
    
    # check if date is greater than another date
    print('Date_1:', d1, 'Date_3:', d3, 'Date_4:', d4)
    print('date_1 is greater than date_3:', d1 > d3)
    print('date_1 is greater than date_4:', d1 > d4)
    
    # check if date is less than another date
    print('Date_1:', d1, 'Date_3:', d3, 'Date_4:', d4)
    print('date_1 is less than date_3:', d1 < d3)
    print('date_1 is less than date_4:', d1 < d4)
    
    # date not equal to check
    print('Date_1:', d1, 'Date_2:', d2, 'Date__3:', d3)
    print('Date_1 and Date_2 are NOT equal:', d1 != d2)
    print('Date_1 and Date_3 are NOT equal:', d1 != d3)
    2 để chỉ trích xuất phần ngày tháng từ đối tượng datetime

  5. So sánh hai thời gian

    Để chỉ so sánh thời gian của đối tượng DateTime, hãy sử dụng phương thức

    from datetime import datetime
    
    # input dates
    d1 = datetime(2022, 6, 27).date()
    d2 = datetime(2022, 6, 27).date()
    d3 = datetime(2021, 5, 14).date()
    d4 = datetime(2022, 10, 10).date()
    
    # omit .date() function if you want to compare the entire datetime object
    # use .date() id you want to compare only the date part of it
    
    # date equality check
    print('Date_1:', d1, 'Date_2:', d2, 'Date3:', d3)
    print('Date_1 and Date_2 are equal:', d1 == d2)
    print('Date_1 and Date_3 are equal:', d1 == d3)
    
    # check if date is greater than another date
    print('Date_1:', d1, 'Date_3:', d3, 'Date_4:', d4)
    print('date_1 is greater than date_3:', d1 > d3)
    print('date_1 is greater than date_4:', d1 > d4)
    
    # check if date is less than another date
    print('Date_1:', d1, 'Date_3:', d3, 'Date_4:', d4)
    print('date_1 is less than date_3:', d1 < d3)
    print('date_1 is less than date_4:', d1 < d4)
    
    # date not equal to check
    print('Date_1:', d1, 'Date_2:', d2, 'Date__3:', d3)
    print('Date_1 and Date_2 are NOT equal:', d1 != d2)
    print('Date_1 and Date_3 are NOT equal:', d1 != d3)
    3 để chỉ trích xuất phần thời gian từ đối tượng datetime

ví dụ 1. So sánh hai ngày giờ

Trong ví dụ này, chúng tôi sẽ kiểm tra

  • Nếu datetime_1 lớn hơn datetime khác
  • Nếu datetime _1 thấp hơn datetime _2
from datetime import datetime

def compare_dates(date1, date2):
    print('Date1:', date1)
    print('Date2:', date2)

    if date1 > date2:
        print('Date1 is greater than date2')
    else:
        print('Date1 is lower than date2')

dt1 = datetime(2022, 9, 13)
# today's datetime
today = datetime.now()
compare_dates(dt1, today)

dt1 = datetime(2022, 9, 13)
dt2 = datetime(2021, 11, 23)
compare_dates(dt1, dt2)

đầu ra

Date1: 2022-09-13 00:00:00
Date2: 2022-10-07 15:12:52.970943
Date1 is lower than date2

Date1: 2022-09-13 00:00:00
Date2: 2021-11-23 00:00:00
Date1 is greater than date2

ví dụ 2. So sánh hai ngày

Giả sử bạn có hai đối tượng datetime. Một cái chỉ có ngày và cái còn lại có các phần ngày & giờ và bạn chỉ muốn so sánh ngày (chứ không phải thời gian)

Bây giờ, nếu bạn chỉ muốn so sánh ngày của các đối tượng DateTime, chỉ cần sử dụng phương thức

from datetime import datetime

# input dates
d1 = datetime(2022, 6, 27).date()
d2 = datetime(2022, 6, 27).date()
d3 = datetime(2021, 5, 14).date()
d4 = datetime(2022, 10, 10).date()

# omit .date() function if you want to compare the entire datetime object
# use .date() id you want to compare only the date part of it

# date equality check
print('Date_1:', d1, 'Date_2:', d2, 'Date3:', d3)
print('Date_1 and Date_2 are equal:', d1 == d2)
print('Date_1 and Date_3 are equal:', d1 == d3)

# check if date is greater than another date
print('Date_1:', d1, 'Date_3:', d3, 'Date_4:', d4)
print('date_1 is greater than date_3:', d1 > d3)
print('date_1 is greater than date_4:', d1 > d4)

# check if date is less than another date
print('Date_1:', d1, 'Date_3:', d3, 'Date_4:', d4)
print('date_1 is less than date_3:', d1 < d3)
print('date_1 is less than date_4:', d1 < d4)

# date not equal to check
print('Date_1:', d1, 'Date_2:', d2, 'Date__3:', d3)
print('Date_1 and Date_2 are NOT equal:', d1 != d2)
print('Date_1 and Date_3 are NOT equal:', d1 != d3)
2 để chỉ trích xuất phần ngày từ đối tượng datetime

from datetime import datetime

# input dates
d1 = datetime(2022, 6, 27).date()
d2 = datetime(2022, 6, 27).date()
d3 = datetime(2021, 5, 14).date()
d4 = datetime(2022, 10, 10).date()

# omit .date() function if you want to compare the entire datetime object
# use .date() id you want to compare only the date part of it

# date equality check
print('Date_1:', d1, 'Date_2:', d2, 'Date3:', d3)
print('Date_1 and Date_2 are equal:', d1 == d2)
print('Date_1 and Date_3 are equal:', d1 == d3)

# check if date is greater than another date
print('Date_1:', d1, 'Date_3:', d3, 'Date_4:', d4)
print('date_1 is greater than date_3:', d1 > d3)
print('date_1 is greater than date_4:', d1 > d4)

# check if date is less than another date
print('Date_1:', d1, 'Date_3:', d3, 'Date_4:', d4)
print('date_1 is less than date_3:', d1 < d3)
print('date_1 is less than date_4:', d1 < d4)

# date not equal to check
print('Date_1:', d1, 'Date_2:', d2, 'Date__3:', d3)
print('Date_1 and Date_2 are NOT equal:', d1 != d2)
print('Date_1 and Date_3 are NOT equal:', d1 != d3)

đầu ra

Date_1: 2022-06-27 Date_2: 2022-06-27 Date3: 2021-05-14
Date_1 and Date_2 are equal: True
Date_1 and Date_3 are equal: False

Date_1: 2022-06-27 Date_3: 2021-05-14 Date_4: 2022-10-10
date_1 is greater than date_3: True
date_1 is greater than date_4: False

Date_1: 2022-06-27 Date_3: 2021-05-14 Date_4: 2022-10-10
date_1 is less than date_3: False
date_1 is less than date_4: True

Date_1: 2022-06-27 Date_2: 2022-06-27 Date__3: 2021-05-14
Date_1 and Date_2 are NOT equal: False
Date_1 and Date_3 are NOT equal: True

ví dụ 3. So sánh thời gian của hai đối tượng DateTime

Giả sử bạn có hai đối tượng datetime. Một cái chỉ có thời gian và cái còn lại có các phần ngày & giờ và bạn chỉ muốn so sánh thời gian (chứ không phải ngày)

Sử dụng phương thức

from datetime import datetime

# input dates
d1 = datetime(2022, 6, 27).date()
d2 = datetime(2022, 6, 27).date()
d3 = datetime(2021, 5, 14).date()
d4 = datetime(2022, 10, 10).date()

# omit .date() function if you want to compare the entire datetime object
# use .date() id you want to compare only the date part of it

# date equality check
print('Date_1:', d1, 'Date_2:', d2, 'Date3:', d3)
print('Date_1 and Date_2 are equal:', d1 == d2)
print('Date_1 and Date_3 are equal:', d1 == d3)

# check if date is greater than another date
print('Date_1:', d1, 'Date_3:', d3, 'Date_4:', d4)
print('date_1 is greater than date_3:', d1 > d3)
print('date_1 is greater than date_4:', d1 > d4)

# check if date is less than another date
print('Date_1:', d1, 'Date_3:', d3, 'Date_4:', d4)
print('date_1 is less than date_3:', d1 < d3)
print('date_1 is less than date_4:', d1 < d4)

# date not equal to check
print('Date_1:', d1, 'Date_2:', d2, 'Date__3:', d3)
print('Date_1 and Date_2 are NOT equal:', d1 != d2)
print('Date_1 and Date_3 are NOT equal:', d1 != d3)
3 để chỉ trích xuất phần thời gian từ đối tượng datetime

Ví dụ

from datetime import datetime

# date in yyyy/-mm-dd hh:mm:ss format
dt_1 = datetime(2022, 6, 27, 18, 45, 53)
dt_2 = datetime(2022, 6, 27, 21, 12, 34)

# use .time() if you want to compare only the time part of it

# date equality check
print('Time_1:', dt_1.time(), 'Time_2:', dt_2.time())

print('Both times are equal:', dt_1.time() == dt_2.time())
print('Times not equal:', dt_1.time() != dt_2.time())

print('Time_1 is greater than Time_2:', dt_1.time() > dt_2.time())
print('Time_1 is less than Time_2:', dt_1.time() < dt_2.time())

đầu ra

Time_1: 18:45:53 Time_2: 21:12:34

Both times are equal: False
Times not equal: True

Time_1 is greater than Time_2: False
Time_1 is less than Time_2: True

So sánh hai chuỗi ngày

Có thể có trường hợp ngày ở định dạng chuỗi. Trước khi so sánh chúng, chúng ta cần chuyển đổi cả hai chuỗi ngày thành đối tượng ngày giờ

Sử dụng hàm 

Date1: 2022-09-13 00:00:00
Date2: 2022-10-07 15:12:52.970943
Date1 is lower than date2

Date1: 2022-09-13 00:00:00
Date2: 2021-11-23 00:00:00
Date1 is greater than date2
2 để chuyển đổi chuỗi ngày thành đối tượng ngày giờ theo 
Date1: 2022-09-13 00:00:00
Date2: 2022-10-07 15:12:52.970943
Date1 is lower than date2

Date1: 2022-09-13 00:00:00
Date2: 2021-11-23 00:00:00
Date1 is greater than date2
3 tương ứng. Các mã định dạng là các chỉ thị tiêu chuẩn để đề cập đến định dạng chuỗi để phân tích cú pháp. Ví dụ: mã định dạng 
Date1: 2022-09-13 00:00:00
Date2: 2022-10-07 15:12:52.970943
Date1 is lower than date2

Date1: 2022-09-13 00:00:00
Date2: 2021-11-23 00:00:00
Date1 is greater than date2
4 dành cho 
Date1: 2022-09-13 00:00:00
Date2: 2022-10-07 15:12:52.970943
Date1 is lower than date2

Date1: 2022-09-13 00:00:00
Date2: 2021-11-23 00:00:00
Date1 is greater than date2
5

Ví dụ

from datetime import datetime

def compare_dates(date1, date2):
    # convert string to date
    dt_obj1 = datetime.strptime(date1, "%Y-%m-%d %H:%M:%S")
    dt_obj2 = datetime.strptime(date2, "%Y-%m-%d %H:%M:%S")
    print('Date1:', dt_obj1)
    print('Date2:', dt_obj2)

    if dt_obj1 == dt_obj2:
        print('Both dates are equal')
    elif dt_obj1 > dt_obj2:
        print('Date1 is greater than date2')
    else:
        print('Date1 is lower than date2')

# datetime in yyyy-mm-dd hh:mm:ss format
dt_str1 = '2022-10-29 8:32:49'
dt_str2 = '2022-5-7 4:14:58'
compare_dates(dt1_str1, dt2_str2)

đầu ra

Date1: 2022-10-29 08:32:49
Date2: 2022-05-07 04:14:58
Date1 is greater than date2

So sánh hai dấu thời gian trong Python

Dấu thời gian là thông tin được mã hóa thường được sử dụng trong UNIX, cho biết ngày và giờ xảy ra một sự kiện cụ thể. Thông tin này có thể chính xác đến từng micro giây. Đó là dấu thời gian POSIX tương ứng với phiên bản datetime

Để so sánh các đối tượng dấu thời gian trong Python, chúng ta có thể sử dụng cùng một toán tử điều kiện mà chúng ta đã sử dụng để so sánh ngày tháng