Bởi vì ISO 8601 cho phép nhiều biến thể của các dấu chấm và dấu gạch ngang tùy chọn, về cơ bản là
import datetime
print ['Current date/time: {}'.format[datetime.datetime.now[]]]
3. Nếu bạn muốn sử dụng Strptime, bạn cần loại bỏ các biến thể đó trước.Mục tiêu là tạo ra một đối tượng DateTime UTC.
Nếu bạn chỉ muốn một trường hợp cơ bản làm việc cho UTC với hậu tố Z như
import datetime
print ['Current date/time: {}'.format[datetime.datetime.now[]]]
4:datetime.datetime.strptime[timestamp.translate[None, ':-'], "%Y%m%dT%H%M%S.%fZ"]
Nếu bạn muốn xử lý các lần bù thời gian như
import datetime
print ['Current date/time: {}'.format[datetime.datetime.now[]]]
5 hoặc import datetime
print ['Current date/time: {}'.format[datetime.datetime.now[]]]
6, hãy sử dụng các phần sau. Chúng sẽ chuyển đổi tất cả các biến thể thành một cái gì đó mà không cần phân cách biến như import datetime
print ['Current date/time: {}'.format[datetime.datetime.now[]]]
7 làm cho nó phù hợp hơn/dễ phân tích hơn.import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
datetime.datetime.strptime[conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" ]
Nếu hệ thống của bạn không hỗ trợ chỉ thị
import datetime
print ['Current date/time: {}'.format[datetime.datetime.now[]]]
8 Strptime [bạn sẽ thấy một cái gì đó như import datetime
print ['Current date/time: {}'.format[datetime.datetime.now[]]]
9] thì bạn cần phải bù thủ công thời gian từ $ python3 datetime-print-1.py
Current date/time: 2018-06-29 08:15:27.243860
0 [UTC]. Lưu ý import datetime
print ['Current date/time: {}'.format[datetime.datetime.now[]]]
8 có thể không hoạt động trên hệ thống của bạn trong các phiên bản Python "%b %d %Y at %I:%M%p"
"September 18, 2017, 22:19:55" -> "%B %d, %Y, %H:%M:%S"
"Sun,05/12/99,12:30PM" -> "%a,%d/%m/%y,%I:%M%p"
"Mon, 21 March, 2015" -> "%a, %d %B, %Y"
"2018-03-12T10:12:45Z" -> "%Y-%m-%dT%H:%M:%SZ"
Bạn có thể phân tích một chuỗi thời gian ngày của bất kỳ định dạng nào bằng cách sử dụng bảng được đề cập trong tài liệu Strptime.
Đối phó với thời gian và DateTime
Xử lý thời gian ngày trở nên phức tạp hơn trong khi đối phó với múi giờ. Tất cả các ví dụ trên chúng tôi đã thảo luận là các đối tượng
$ python3 datetime-print-1.py
Current date/time: 2018-06-29 08:15:27.243860
2 ngây thơ, tức là các đối tượng này không chứa bất kỳ dữ liệu liên quan đến timezone nào. Đối tượng $ python3 datetime-print-1.py
Current date/time: 2018-06-29 08:15:27.243860
2 có một biến chứa thông tin múi giờ, import datetime
date_time_str = 'Jun 28 2018 7:40AM'
date_time_obj = datetime.datetime.strptime[date_time_str, '%b %d %Y %I:%M%p']
print['Date:', date_time_obj.date[]]
print['Time:', date_time_obj.time[]]
print['Date-time:', date_time_obj]
5.import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
datetime.datetime.strptime[conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" ]
0Mã này sẽ in:
import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
datetime.datetime.strptime[conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" ]
1Đầu ra của
import datetime
date_time_str = 'Jun 28 2018 7:40AM'
date_time_obj = datetime.datetime.strptime[date_time_str, '%b %d %Y %I:%M%p']
print['Date:', date_time_obj.date[]]
print['Time:', date_time_obj.time[]]
print['Date-time:', date_time_obj]
5 là import datetime
date_time_str = 'Jun 28 2018 7:40AM'
date_time_obj = datetime.datetime.strptime[date_time_str, '%b %d %Y %I:%M%p']
print['Date:', date_time_obj.date[]]
print['Time:', date_time_obj.time[]]
print['Date-time:', date_time_obj]
7 vì nó là một đối tượng $ python3 datetime-print-1.py
Current date/time: 2018-06-29 08:15:27.243860
2 ngây thơ. Để chuyển đổi timezone, một thư viện có tên import datetime
date_time_str = 'Jun 28 2018 7:40AM'
date_time_obj = datetime.datetime.strptime[date_time_str, '%b %d %Y %I:%M%p']
print['Date:', date_time_obj.date[]]
print['Time:', date_time_obj.time[]]
print['Date-time:', date_time_obj]
9 có sẵn cho Python. Bạn có thể cài đặt nó như mô tả trong các hướng dẫn này. Bây giờ, chúng ta hãy sử dụng thư viện import datetime
date_time_str = 'Jun 28 2018 7:40AM'
date_time_obj = datetime.datetime.strptime[date_time_str, '%b %d %Y %I:%M%p']
print['Date:', date_time_obj.date[]]
print['Time:', date_time_obj.time[]]
print['Date-time:', date_time_obj]
9 để chuyển đổi dấu thời gian ở trên sang UTC.import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
datetime.datetime.strptime[conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" ]
2Output:
import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
datetime.datetime.strptime[conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" ]
3$ python3 datetime-print-3.py
Date: 2018-06-28
Time: 07:40:00
Date-time: 2018-06-28 07:40:00
1 là sự khác biệt giữa thời gian hiển thị và thời gian UTC. Trong ví dụ này, giá trị của import datetime
date_time_str = 'Jun 28 2018 7:40AM'
date_time_obj = datetime.datetime.strptime[date_time_str, '%b %d %Y %I:%M%p']
print['Date:', date_time_obj.date[]]
print['Time:', date_time_obj.time[]]
print['Date-time:', date_time_obj]
5 cũng xảy ra với UTC, do đó bù $ python3 datetime-print-3.py
Date: 2018-06-28
Time: 07:40:00
Date-time: 2018-06-28 07:40:00
3. Trong trường hợp này, đối tượng $ python3 datetime-print-1.py
Current date/time: 2018-06-29 08:15:27.243860
2 là một đối tượng nhận biết múi giờ.Tương tự, chúng ta có thể chuyển đổi chuỗi thời gian ngày thành bất kỳ múi giờ nào khác. Ví dụ: chúng ta có thể chuyển đổi chuỗi "2018-06-29 17: 08: 00.586525+00: 00" thành timezone "America/new_york", như được hiển thị bên dưới:
import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
datetime.datetime.strptime[conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" ]
4Output:
import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
datetime.datetime.strptime[conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" ]
5Đầu tiên, chúng tôi đã chuyển đổi chuỗi thành đối tượng
$ python3 datetime-print-1.py
Current date/time: 2018-06-29 08:15:27.243860
2, import datetime
date_time_str = '2018-06-29 08:15:27.243860'
date_time_obj = datetime.datetime.strptime[date_time_str, '%Y-%m-%d %H:%M:%S.%f']
print['Date:', date_time_obj.date[]]
print['Time:', date_time_obj.time[]]
print['Date-time:', date_time_obj]
8. Sau đó, chúng tôi đã chuyển đổi nó thành một đối tượng $ python3 datetime-print-1.py
Current date/time: 2018-06-29 08:15:27.243860
2 hỗ trợ thời gian, $ python3 datetime-print-3.py
Date: 2018-06-28
Time: 07:40:00
Date-time: 2018-06-28 07:40:00
8. Vì chúng tôi đã đặt timezone là "America/new_york", thời gian đầu ra cho thấy rằng nó ở phía sau 4 giờ so với thời gian UTC. Bạn có thể kiểm tra trang Wikipedia này để tìm danh sách đầy đủ các múi giờ có sẵn.Chuyển đổi thời gian
Chúng ta có thể chuyển đổi múi giờ của đối tượng
$ python3 datetime-print-1.py
Current date/time: 2018-06-29 08:15:27.243860
2 từ vùng này sang vùng khác, như được hiển thị trong ví dụ dưới đây:import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
datetime.datetime.strptime[conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" ]
6Đầu tiên, chúng tôi đã tạo một đối tượng DateTime với thời gian hiện tại và đặt nó là múi giờ "America/new_york". Sau đó, sử dụng phương pháp
"Jun 28 2018 at 7:40AM" -> "%b %d %Y at %I:%M%p"
"September 18, 2017, 22:19:55" -> "%B %d, %Y, %H:%M:%S"
"Sun,05/12/99,12:30PM" -> "%a,%d/%m/%y,%I:%M%p"
"Mon, 21 March, 2015" -> "%a, %d %B, %Y"
"2018-03-12T10:12:45Z" -> "%Y-%m-%dT%H:%M:%SZ"
0, chúng tôi đã chuyển đổi thời gian $ python3 datetime-print-1.py
Current date/time: 2018-06-29 08:15:27.243860
2 này thành timezone "Châu Âu/London". Cả hai $ python3 datetime-print-1.py
Current date/time: 2018-06-29 08:15:27.243860
2 sẽ in các giá trị khác nhau như:Kiểm tra hướng dẫn thực hành của chúng tôi, thực tế để học Git, với các thực hành tốt nhất, các tiêu chuẩn được công nghiệp chấp nhận và bao gồm bảng gian lận. Ngừng các lệnh git googling và thực sự tìm hiểu nó!
import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
datetime.datetime.strptime[conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" ]
7Đúng như dự đoán, thời gian ngày khác nhau vì chúng cách nhau khoảng 5 giờ.
Sử dụng thư viện của bên thứ ba
Mô -đun
$ python3 datetime-print-1.py
Current date/time: 2018-06-29 08:15:27.243860
2 của Python có thể chuyển đổi tất cả các loại chuỗi khác nhau thành đối tượng $ python3 datetime-print-1.py
Current date/time: 2018-06-29 08:15:27.243860
2. Nhưng vấn đề chính là để làm điều này, bạn cần tạo chuỗi mã định dạng phù hợp mà import datetime
date_time_str = '2018-06-29 08:15:27.243860'
date_time_obj = datetime.datetime.strptime[date_time_str, '%Y-%m-%d %H:%M:%S.%f']
print['Date:', date_time_obj.date[]]
print['Time:', date_time_obj.time[]]
print['Date-time:', date_time_obj]
2 có thể hiểu. Tạo chuỗi này cần có thời gian và nó làm cho mã khó đọc hơn. Thay vào đó, chúng tôi có thể sử dụng các thư viện của bên thứ ba khác để làm cho nó dễ dàng hơn.Trong một số trường hợp, các thư viện của bên thứ ba này cũng có hỗ trợ tích hợp tốt hơn để thao tác và so sánh thời gian ngày, và một số thậm chí có thời gian được tích hợp theo thời gian, vì vậy bạn không cần phải bao gồm một gói bổ sung.
Chúng ta hãy xem một vài trong số các thư viện này trong các phần sau.
ngày
Mô -đun DateUtil là một phần mở rộng cho mô -đun
$ python3 datetime-print-1.py
Current date/time: 2018-06-29 08:15:27.243860
2. Một lợi thế là chúng ta không cần chuyển bất kỳ mã phân tích cú pháp nào để phân tích chuỗi. Ví dụ:import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
datetime.datetime.strptime[conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" ]
8Hàm
"Jun 28 2018 at 7:40AM" -> "%b %d %Y at %I:%M%p"
"September 18, 2017, 22:19:55" -> "%B %d, %Y, %H:%M:%S"
"Sun,05/12/99,12:30PM" -> "%a,%d/%m/%y,%I:%M%p"
"Mon, 21 March, 2015" -> "%a, %d %B, %Y"
"2018-03-12T10:12:45Z" -> "%Y-%m-%dT%H:%M:%SZ"
7 này sẽ tự động phân tích chuỗi và lưu trữ nó trong biến $ python3 datetime-print-1.py
Current date/time: 2018-06-29 08:15:27.243860
2. Phân tích cú pháp được thực hiện tự động. Bạn không cần phải đề cập đến bất kỳ chuỗi định dạng nào. Hãy cố gắng phân tích các loại chuỗi khác nhau bằng cách sử dụng "Jun 28 2018 at 7:40AM" -> "%b %d %Y at %I:%M%p"
"September 18, 2017, 22:19:55" -> "%B %d, %Y, %H:%M:%S"
"Sun,05/12/99,12:30PM" -> "%a,%d/%m/%y,%I:%M%p"
"Mon, 21 March, 2015" -> "%a, %d %B, %Y"
"2018-03-12T10:12:45Z" -> "%Y-%m-%dT%H:%M:%SZ"
9:import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
datetime.datetime.strptime[conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" ]
9Output:
import re
import datetime
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
# Split on the offset to remove it. Use a capture group to keep the delimiter
split_timestamp = re.split[r"[[+|-]]",conformed_timestamp]
main_timestamp = split_timestamp[0]
if len[split_timestamp] == 3:
sign = split_timestamp[1]
offset = split_timestamp[2]
else:
sign = None
offset = None
# Generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime[main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" ]
if offset:
# Create timedelta based on offset
offset_delta = datetime.timedelta[hours=int[sign+offset[:-2]], minutes=int[sign+offset[-2:]]]
# Offset datetime with timedelta
output_datetime = output_datetime + offset_delta
0Bạn có thể thấy rằng hầu hết mọi loại chuỗi có thể được phân tích dễ dàng bằng mô -đun
"Jun 28 2018 at 7:40AM" -> "%b %d %Y at %I:%M%p"
"September 18, 2017, 22:19:55" -> "%B %d, %Y, %H:%M:%S"
"Sun,05/12/99,12:30PM" -> "%a,%d/%m/%y,%I:%M%p"
"Mon, 21 March, 2015" -> "%a, %d %B, %Y"
"2018-03-12T10:12:45Z" -> "%Y-%m-%dT%H:%M:%SZ"
9.Mặc dù điều này thuận tiện, nhưng hãy nhớ lại từ trước đó rằng phải dự đoán định dạng làm cho mã chậm hơn nhiều, vì vậy nếu mã của bạn yêu cầu hiệu suất cao thì đây có thể không phải là cách tiếp cận phù hợp cho ứng dụng của bạn.
Maya
Maya cũng làm cho nó rất dễ phân tích một chuỗi và để thay đổi thời gian. Một số ví dụ đơn giản được hiển thị ở đây:
import re
import datetime
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
# Split on the offset to remove it. Use a capture group to keep the delimiter
split_timestamp = re.split[r"[[+|-]]",conformed_timestamp]
main_timestamp = split_timestamp[0]
if len[split_timestamp] == 3:
sign = split_timestamp[1]
offset = split_timestamp[2]
else:
sign = None
offset = None
# Generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime[main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" ]
if offset:
# Create timedelta based on offset
offset_delta = datetime.timedelta[hours=int[sign+offset[:-2]], minutes=int[sign+offset[-2:]]]
# Offset datetime with timedelta
output_datetime = output_datetime + offset_delta
1Output:
import re
import datetime
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
# Split on the offset to remove it. Use a capture group to keep the delimiter
split_timestamp = re.split[r"[[+|-]]",conformed_timestamp]
main_timestamp = split_timestamp[0]
if len[split_timestamp] == 3:
sign = split_timestamp[1]
offset = split_timestamp[2]
else:
sign = None
offset = None
# Generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime[main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" ]
if offset:
# Create timedelta based on offset
offset_delta = datetime.timedelta[hours=int[sign+offset[:-2]], minutes=int[sign+offset[-2:]]]
# Offset datetime with timedelta
output_datetime = output_datetime + offset_delta
2Để chuyển đổi thời gian sang một múi giờ khác:
import re
import datetime
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
# Split on the offset to remove it. Use a capture group to keep the delimiter
split_timestamp = re.split[r"[[+|-]]",conformed_timestamp]
main_timestamp = split_timestamp[0]
if len[split_timestamp] == 3:
sign = split_timestamp[1]
offset = split_timestamp[2]
else:
sign = None
offset = None
# Generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime[main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" ]
if offset:
# Create timedelta based on offset
offset_delta = datetime.timedelta[hours=int[sign+offset[:-2]], minutes=int[sign+offset[-2:]]]
# Offset datetime with timedelta
output_datetime = output_datetime + offset_delta
3Output:
import re
import datetime
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
# Split on the offset to remove it. Use a capture group to keep the delimiter
split_timestamp = re.split[r"[[+|-]]",conformed_timestamp]
main_timestamp = split_timestamp[0]
if len[split_timestamp] == 3:
sign = split_timestamp[1]
offset = split_timestamp[2]
else:
sign = None
offset = None
# Generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime[main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" ]
if offset:
# Create timedelta based on offset
offset_delta = datetime.timedelta[hours=int[sign+offset[:-2]], minutes=int[sign+offset[-2:]]]
# Offset datetime with timedelta
output_datetime = output_datetime + offset_delta
4Bây giờ không phải là dễ sử dụng? Hãy thử
import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
datetime.datetime.strptime[conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" ]
01 với cùng một bộ chuỗi chúng tôi đã sử dụng với "Jun 28 2018 at 7:40AM" -> "%b %d %Y at %I:%M%p"
"September 18, 2017, 22:19:55" -> "%B %d, %Y, %H:%M:%S"
"Sun,05/12/99,12:30PM" -> "%a,%d/%m/%y,%I:%M%p"
"Mon, 21 March, 2015" -> "%a, %d %B, %Y"
"2018-03-12T10:12:45Z" -> "%Y-%m-%dT%H:%M:%SZ"
9:import re
import datetime
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
# Split on the offset to remove it. Use a capture group to keep the delimiter
split_timestamp = re.split[r"[[+|-]]",conformed_timestamp]
main_timestamp = split_timestamp[0]
if len[split_timestamp] == 3:
sign = split_timestamp[1]
offset = split_timestamp[2]
else:
sign = None
offset = None
# Generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime[main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" ]
if offset:
# Create timedelta based on offset
offset_delta = datetime.timedelta[hours=int[sign+offset[:-2]], minutes=int[sign+offset[-2:]]]
# Offset datetime with timedelta
output_datetime = output_datetime + offset_delta
5Output:
import re
import datetime
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
# Split on the offset to remove it. Use a capture group to keep the delimiter
split_timestamp = re.split[r"[[+|-]]",conformed_timestamp]
main_timestamp = split_timestamp[0]
if len[split_timestamp] == 3:
sign = split_timestamp[1]
offset = split_timestamp[2]
else:
sign = None
offset = None
# Generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime[main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" ]
if offset:
# Create timedelta based on offset
offset_delta = datetime.timedelta[hours=int[sign+offset[:-2]], minutes=int[sign+offset[-2:]]]
# Offset datetime with timedelta
output_datetime = output_datetime + offset_delta
6Như bạn có thể thấy, tất cả các định dạng ngày đã được phân tích thành công.
Nhưng bạn có nhận thấy sự khác biệt không? Nếu chúng tôi không cung cấp thông tin múi giờ thì nó sẽ tự động chuyển đổi nó thành UTC. Vì vậy, điều quan trọng cần lưu ý là chúng tôi phải cung cấp các tham số
import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
datetime.datetime.strptime[conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" ]
03 và import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
datetime.datetime.strptime[conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" ]
04 nếu thời gian không có trong UTC.Mũi tên
Mũi tên là một thư viện khác để xử lý DateTime trong Python. Và giống như trước đây với
import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
datetime.datetime.strptime[conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" ]
01, nó cũng tự động tìm ra định dạng DateTime. Sau khi được giải thích, nó trả về một đối tượng Python $ python3 datetime-print-1.py
Current date/time: 2018-06-29 08:15:27.243860
2 từ đối tượng import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
datetime.datetime.strptime[conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" ]
07.Hãy thử điều này với cùng một chuỗi ví dụ mà chúng tôi đã sử dụng cho
import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
datetime.datetime.strptime[conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" ]
01:import re
import datetime
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
# Split on the offset to remove it. Use a capture group to keep the delimiter
split_timestamp = re.split[r"[[+|-]]",conformed_timestamp]
main_timestamp = split_timestamp[0]
if len[split_timestamp] == 3:
sign = split_timestamp[1]
offset = split_timestamp[2]
else:
sign = None
offset = None
# Generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime[main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" ]
if offset:
# Create timedelta based on offset
offset_delta = datetime.timedelta[hours=int[sign+offset[:-2]], minutes=int[sign+offset[-2:]]]
# Offset datetime with timedelta
output_datetime = output_datetime + offset_delta
7Output:
import re
import datetime
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
# Split on the offset to remove it. Use a capture group to keep the delimiter
split_timestamp = re.split[r"[[+|-]]",conformed_timestamp]
main_timestamp = split_timestamp[0]
if len[split_timestamp] == 3:
sign = split_timestamp[1]
offset = split_timestamp[2]
else:
sign = None
offset = None
# Generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime[main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" ]
if offset:
# Create timedelta based on offset
offset_delta = datetime.timedelta[hours=int[sign+offset[:-2]], minutes=int[sign+offset[-2:]]]
# Offset datetime with timedelta
output_datetime = output_datetime + offset_delta
8Và đây là cách bạn có thể sử dụng
import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
datetime.datetime.strptime[conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" ]
07 để chuyển đổi thời gian bằng phương pháp import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
datetime.datetime.strptime[conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" ]
10:import re
import datetime
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub[r"[:]|[[-][?![[\d{2}[:]\d{2}]|[\d{4}]]$]]", '', timestamp]
# Split on the offset to remove it. Use a capture group to keep the delimiter
split_timestamp = re.split[r"[[+|-]]",conformed_timestamp]
main_timestamp = split_timestamp[0]
if len[split_timestamp] == 3:
sign = split_timestamp[1]
offset = split_timestamp[2]
else:
sign = None
offset = None
# Generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime[main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" ]
if offset:
# Create timedelta based on offset
offset_delta = datetime.timedelta[hours=int[sign+offset[:-2]], minutes=int[sign+offset[-2:]]]
# Offset datetime with timedelta
output_datetime = output_datetime + offset_delta
9Output:
import datetime
print ['Current date/time: {}'.format[datetime.datetime.now[]]]
0Như bạn có thể thấy chuỗi thời gian ngày được chuyển đổi thành khu vực "America/new_york".
Bây giờ, chúng ta hãy sử dụng cùng một bộ chuỗi mà chúng ta đã sử dụng ở trên:
import datetime
print ['Current date/time: {}'.format[datetime.datetime.now[]]]
1Mã này sẽ thất bại đối với các chuỗi thời gian đã được nhận xét, đó là hơn một nửa các ví dụ của chúng tôi. Đầu ra cho các chuỗi khác sẽ là:
import datetime
print ['Current date/time: {}'.format[datetime.datetime.now[]]]
2Để phân tích chính xác các chuỗi thời gian mà tôi đã nhận xét, bạn sẽ cần phải vượt qua các mã thông báo định dạng tương ứng để đưa ra manh mối thư viện về cách phân tích cú pháp. Ví dụ: "MMM" cho tên tháng, như "Jan, Feb, Mar", v.v. Bạn có thể kiểm tra hướng dẫn này cho tất cả các mã thông báo có sẵn.
Sự kết luận
Trong bài viết này, chúng tôi đã chỉ ra những cách khác nhau để phân tích một chuỗi vào một đối tượng
$ python3 datetime-print-1.py
Current date/time: 2018-06-29 08:15:27.243860
2 trong Python. Bạn có thể chọn thư viện Python $ python3 datetime-print-1.py
Current date/time: 2018-06-29 08:15:27.243860
2 mặc định hoặc bất kỳ thư viện nào của bên thứ ba được đề cập trong bài viết này, trong số nhiều thư viện khác.Vấn đề chính với gói
$ python3 datetime-print-1.py
Current date/time: 2018-06-29 08:15:27.243860
2 mặc định là chúng ta cần chỉ định mã phân tích cú pháp theo cách thủ công cho hầu hết các định dạng chuỗi thời gian ngày. Vì vậy, nếu định dạng chuỗi của bạn thay đổi trong tương lai, bạn cũng có thể sẽ phải thay đổi mã của mình. Nhưng nhiều thư viện của bên thứ ba, như các thư viện được đề cập ở đây, tự động xử lý nó.Một vấn đề nữa chúng ta gặp phải là xử lý thời gian. Cách tốt nhất để xử lý chúng là luôn luôn lưu trữ thời gian trong cơ sở dữ liệu của bạn dưới dạng định dạng UTC và sau đó chuyển đổi nó thành múi giờ cục bộ của người dùng khi cần.
Các thư viện này không chỉ tốt cho các chuỗi phân tích cú pháp, mà chúng có thể được sử dụng cho rất nhiều loại hoạt động liên quan đến thời gian ngày khác nhau. Tôi khuyến khích bạn đi qua các tài liệu để tìm hiểu chi tiết các chức năng.