• How to Format Dates in Python
  • Nicholas Samuel
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: Raoul1996
  • Proofreader: Rocheers

introduce

Python comes with a variety of useful objects that you can use directly. Date objects are an example. Due to the complexity of dates and times, date types are difficult to manipulate from scratch. Fortunately, Python date objects make it fairly easy to convert dates into the desired string format.

Date formatting is one of your most important tasks as a programmer. Different locales represent dates/times differently, so one of your big goals as a programmer is to display date values in a user-readable way.

For example, you might need to represent the date value in a numeric format, such as “02-23-2018.” On the other hand, you may need to represent the same date in a longer text format (e.g. “Feb 23,2018”). In another case, you might want to extract the month in string format from the date value in numeric format.

In this article, we’ll examine different types of date objects and their capabilities.

Datetime module

As you might guess, Python’s Datetime module contains methods you can use to handle date and time values. To use this module, we need to import it with the following import statement:

import datetime
Copy the code

We can use the time class to represent the time value. The attributes of the time class include hours, minutes, seconds, and microseconds.

Arguments to the time class are optional. Although you will get 0 times (objects) without specifying any parameters, this is unlikely to be what you need most of the time.

For example, to initialize time objects with values of 1 hour, 10 minutes, 20 seconds, and 13 microseconds, we could run the following command:

t = datetime.time(1, 10, 20, 13)
Copy the code

Let’s use the print function to check the time:

print(t)
Copy the code

Output:

01:10:20. 000013Copy the code

You may only need to view hours, minutes, seconds, or microseconds. You can do this as follows:

print('hour:', t.hour)
Copy the code

Output:

hour: 1
Copy the code

Minutes, seconds, or microseconds of the above time (object) can be retrieved as follows:

print('Minutes:', t.minute)
print('Seconds:', t.second)
print('Microsecond:', t.microsecond)
Copy the code

Output:

Minutes: 10
Seconds: 20
Microseconds: 13
Copy the code

A calendar date can be represented by the date class. The attributes that the example has are year, month, and day.

Let’s call the today method to check today’s date:

import datetime

today = datetime.date.today()
print(today)
Copy the code

Output:

2018-09-15
Copy the code

The code will return today’s date, so the output you see depends on the date you ran the script.

Now we call the ctime method to print the date in a different format:

print('ctime:', today.ctime())
Copy the code

Output:

ctime: Sat Sep 15 00:00:00 2018
Copy the code

The ctime method uses a longer date-time format than the examples we’ve seen before. This method is primarily used to convert Unix time (the number of seconds since January 1, 1970) to string format.

Here’s how we use the Date class to display the year, month, and date:

print('Year:', today.year)
print('Month:', today.month)
print('Day :', today.day)
Copy the code

The output

Year: 2018

Month: 9
Day : 15
Copy the code

Use strftime to convert dates to strings

Now that you know how to create time and date objects, let’s learn how to format them into more readable strings.

To do this, we will use the strftime method. This method helps us convert the date object into a readable string. It takes two arguments, and the syntax looks like this:

time.strftime(format, t)
Copy the code

The first argument is the format string (in what format to display the date and time, thanks to Rocheers for reminding), and the second argument is the formatted time, optionally.

This method can also be called directly on a Datetime object. As shown in the following example:

import datetime

x = datetime.datetime(2018, 9, 15)

print(x.strftime("%b %d %Y %H:%M:%S"))
Copy the code

Output:

Sep 15 2018 00:00:00
Copy the code

We use the following string to format the date:

  • %b: Returns the first three characters of the month name. In our case, it returns “Sep”
  • %d: Returns the date of the month, from 1 to 31. In our case, it returns “15”.
  • %Y: Returns the year in four-digit format. In our case, it returns “2018”.
  • %H: Returns the hour. In our case, it returns “00”.
  • %M: Returns minutes from 00 to 59. In our case, it returns “00”.
  • %S: returns seconds from 00 to 59. In our case, it returns “00”.

We have no time (object), so the time values are “00”. The following example shows how to format the time:

import datetime

x = datetime.datetime(2018, 9, 15, 12, 45, 35)

print(x.strftime("%b %d %Y %H:%M:%S"))
Copy the code

Output:

Sep 15 2018 12:45:35
Copy the code

Complete list of character codes

In addition to the string given above, the strftime method uses several other instructions to format the date value:

  • %a: Returns the first three characters of the workday, for example, Wed.
  • %A: Returns the full name of the workday, such as Wednesday.
  • %B: Returns the full name of the month, as in September.
  • %w: Returns weekdays as numbers, 0 through 6, with Sunday being 0.
  • %m: Returns the month as a number, from 01 to 12.
  • %p: Returns the AM/PM identifier.
  • %y: Returns the year in two-digit format, for example, “18” instead of “2018”.
  • %f: returns microseconds from 000000 to 999999.
  • %Z: Returns the time zone.
  • %z: Returns the UTC offset.
  • %j: Returns the date number of the current year, from 001 to 366.
  • %W: Returns the number of weeks of the year, 00 to 53. Monday is counted as the first day of the week.
  • %U: Returns the number of weeks of the year, 00 to 53. Sunday was counted as the first day of the week.
  • %c: Returns the local date and time version.
  • %x: Returns the local date version.
  • %X: Returns the local time version.

Weekday is a weekday, but consider the following example:

from datetime import datetime
x  = datetime.now()
x.strftime("%A")
Copy the code

Output:

'Sunday'
Copy the code

Consider the following example:

import datetime

x = datetime.datetime(2018, 9, 15)

print(x.strftime('%b/%d/%Y'))
Copy the code

Output:

Sep/15/2018
Copy the code

Here’s how you can get months only:

print(x.strftime('%B'))
Copy the code

Output:

September
Copy the code

Let’s just show the year:

print(x.strftime('%Y'))
Copy the code

Output:

2018
Copy the code

In this example, we use the formatting code %Y. Note that its Y is capitalized, now use small notation:

print(x.strftime('%y'))
Copy the code

Output:

18 
Copy the code

This time the first two digits of the year are omitted. As you can see, with this formatting code, you can represent the date and time in any way you want.

Use strptime to convert a string to a date

The strftime method helps us convert a date object into a readable string; strptime does the opposite. It acts on strings and converts them into date objects that Python can understand.

Here is the syntax for this method:

datetime.strptime(string, format)
Copy the code

The string argument is a string value that we convert to date format. The format argument is an instruction that specifies the format to be used for the converted date.

For example, if we need to convert the string “9/15/18” to a Datetime object.

Let’s import the datetime module first. We’ll use the from keyword to be able to reference specific functions in the module without dot formatting:

from datetime import datetime
Copy the code

We can then define dates as strings:

str = '9/15/18'
Copy the code

Python cannot interpret the above string as a datetime until it is converted into an actual Datetime object. We can do this successfully by calling the strptime method:

Execute the following command to convert the string:

date_object = datetime.strptime(str, '%m/%d/%y')
Copy the code

Now let’s call the print function to display the string in datetime format:

print(date_object)
Copy the code

Output:

2018-09-15 00:00:00
Copy the code

As you can see, the conversion is successful!

You can see that the forward slash “/” is used to separate the elements of the string. This tells the Strptime method what format our date is, in our case using a “/” as the separator.

But what if month/day/year is separated by a “-“? Here’s what you should do:

from datetime import datetime

str = '9-15-18'
date_object = datetime.strptime(str, '%m-%d-%y')

print(date_object)
Copy the code

Output:

2018-09-15 00:00:00
Copy the code

Once again, thanks to the format specifier, the Strptime method is able to parse our date and convert it into a date object.

conclusion

In this article, we looked at how to format dates in Python. We saw how the Datetime module in Python manipulates date and time values. The module contains a number of classes that manipulate dates and times, such as the Time class for time values and the Date class for calendar date values.

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.