📅  最后修改于: 2023-12-03 14:45:57.152000             🧑  作者: Mango
Python datetime is a module that allows programmers to work with dates and times. One commonly used format when dealing with dates is the ISO 8601 format, which looks like: 'yyyy-MM-dd'T'HH:mm:ssZ'. In this format, the 'T' separates the date and time components, while the 'Z' indicates the timezone as UTC (Coordinated Universal Time).
To work with this format in Python, you can use the strftime() method to format a datetime object as a string:
import datetime
now = datetime.datetime.utcnow()
formatted_date = now.strftime('%Y-%m-%dT%H:%M:%SZ')
print(formatted_date) # Example output: 2022-01-01T00:00:00Z
You can also use the strptime() method to convert a string representation of the date into a datetime object:
import datetime
date_string = '2022-01-01T00:00:00Z'
datetime_obj = datetime.datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%SZ')
print(datetime_obj) # Example output: 2022-01-01 00:00:00
Note that when using strptime(), you need to pass in the format string that corresponds to the date format you are working with.
In addition to formatting and parsing dates, the datetime module also provides a variety of other functionality, such as timedelta objects for working with time durations, and support for timezones. Overall, the datetime module is an essential tool for any Python programmer who needs to work with dates and times.
In this article, we discussed the 'yyyy-MM-dd'T'HH:mm:ssZ' format, which is commonly used when dealing with dates in the ISO 8601 format. We also looked at how to work with this format in Python using the datetime module. Whether you are building a web application, working on a data analysis project, or performing any other task that involves dates and times, the datetime module is an essential tool for Python programmers.