Python'da Tarihler Nasıl Biçimlendirilir?

Giriş

Python comes with a variety of useful objects that can be used out of the box. Date objects are examples of such objects. Date types are difficult to manipulate from scratch, due to the complexity of dates and times. However, Python date objects make it extremely easy to convert dates into the desirable string formats.

Date formatting is a common task that you will face as a programmer, and communicating dates properly to end users, if your application exposes them, is an important part of UX.

Different regions around the world have different ways of representing dates/times, therefore your goal as a programmer is to present the date values in a way that is readable to the users.

For example, you may need to represent a date value numerically like “02-23-2023”. On the flip side, you may need to write the same date value in a longer textual format like “Feb 23, 2023”. In another scenario, you may want to extract the month in string format from a numerically formated date value.

In this article, we will study different types of date objects along with their functionalities.

The datetime Module

Python'un datetime module contains methods that can be used to work with date and time values. To use this module, we first import it via the import statement as follows:

import datetime

We can represent time values using the time class. The attributes for the time class include the hour, minute, second and microsecond.

Not: için argümanlar time class are optional. Although if you don’t specify any argument you will get back a time of 0, which is unlikely to be what you need most of the time.

For example, you can initialize a time object with a value of 1 hour, 10 minutes, 20 seconds and 13 microseconds using:

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

To see the time, let’s use the print işlevi:

print(t)

To extract fields, such as the hour, minute, second or microsecond – you can access each field respectively:

print('hour:', t.hour)

The minutes, seconds and microseconds for the above time can be retrieved as follows:

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

The values for the calendar date can be represented via the date class. The instances will have attributes for year, month, and day.

arayalım today() method to see today’s date:

import datetime

today = datetime.date.today()
print(today) 

The code will return the date for today, therefore the output you see will depend on the day you run the above script.

Now let’s call the ctime method to print the date in another format:

print('ctime:', today.ctime())

The ctime method uses a longer date-time format than the examples we saw before. This method is primarily used for converting Unix-time (the number of seconds since Jan. 1st, 1970) to a string format.

And here is how we can display the year, the month, and the day using the date sınıf:

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

Bunun sonucu:

Year: 2022
Month: 9
Day : 15

Converting Dates to Strings with strftime()

Now that you know how to create Date and Time objects, let us learn how to format them into more readable strings.

To achieve this, we will be using the strftime() method. This method helps us convert date objects into readable strings. It takes two parameters, as shown in the following syntax:

time.strftime(format, t)

The first parameter is the format string, while the second parameter is the time to be formatted, which is optional.

This method can also be used on a datetime object directly, as shown in the following example:

import datetime

x = datetime.datetime(2022, 9, 15)
print(x.strftime("%b %d %Y %H:%M:%S"))

En iyi uygulamalar, endüstri tarafından kabul edilen standartlar ve dahil edilen hile sayfası ile Git'i öğrenmek için uygulamalı, pratik kılavuzumuza göz atın. Googling Git komutlarını durdurun ve aslında öğrenmek o!

We have used the following character strings to format the date:

  • %b: Returns the first three characters of the month name. In our example, it returned “Sep”.
  • %d: Returns day of the month, from 1 to 31. In our example, it returned “15”.
  • %Y: Returns the year in four-digit format. In our example, it returned “2022”.
  • %H: Returns the hour. In our example, it returned “00”.
  • %M: Returns the minute, from 00 to 59. In our example, it returned “00”.
  • %S: Returns the second, from 00 to 59. In our example, it returned “00”.

We did not pass a time, hence the values for time are all “00”. The following example shows how the time can be formatted as well:

import datetime

x = datetime.datetime(2022, 9, 15, 12, 45, 35)
print(x.strftime("%b %d %Y %H:%M:%S"))

The Complete Character Code List

Other than the character strings given above, the strftime method takes several other directives for formatting date values:

  • %a: Returns the first three characters of the weekday, e.g. Wed.
  • %A: Returns the full name of the weekday, e.g. Wednesday.
  • %B: Returns the full name of the month, e.g. September.
  • %w: Returns the weekday as a number, from 0 to 6, with Sunday being 0.
  • %m: Returns the month as a number, from 01 to 12.
  • %p: Returns AM/PM for time.
  • %y: Returns the year in two-digit format, that is, without the century. For example, “18” instead of “2018”.
  • %f: Returns microsecond from 000000 to 999999.
  • %Z: Returns the timezone.
  • %z: Returns UTC offset.
  • %j: Returns the number of the day in the year, from 001 to 366.
  • %W: Returns the week number of the year, from 00 to 53, with Monday being counted as the first day of the week.
  • %U: Returns the week number of the year, from 00 to 53, with Sunday counted as the first day of each week.
  • %c: Returns the local date and time version.
  • %x: Returns the local version of date.
  • %X: Returns the local version of time.

Aşağıdaki örneği düşünün:

import datetime

x = datetime.datetime(2022, 9, 15)
print(x.strftime('%b/%d/%Y'))

And here is how you can get the month only:

print(x.strftime('%B'))

Let us display the year:

print(x.strftime('%Y'))

In this example we have used the format code %Y. Notice that the Y is in uppercase. Now write it in lowercase:

print(x.strftime('%y'))

As you can see, with these formatting codes you can represent the date-time in just about any form that you’d like.

Converting Strings to Dates with strptime

The strftime() method helped us convert date objects into more readable strings. The strptime() method does the opposite, that is, it takes strings and converts them into date objects that Python can understand.

This is useful when you receive a string-formatted date, and wish to convert it to a different string-formatted date. By converting to an intermediary datetime object, you gain access to a parsed structure that can be reformatted to any other format.

Here is the syntax for the method:

datetime.strptime(string, format)

The string parameter is the value in string format that we want to convert into date format. The format parameter is the directive specifying the format to be taken by the date after the conversion.

For example, let’s say we need to convert the string “9/15/22” into a datetime nesne.

Let’s first import the datetime modülü:

from datetime import datetime

We can then define the date in the form of a string:

str = '9/15/22'

Python will not be able to understand the above string as a datetime until we convert it to an actual datetime object. We can successfully do so by calling the strptime yöntemi.

Execute the following command to convert the string:

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

Let’s now call the print function to display the string in datetime biçimi:

print(date_object)

As you can see, the conversion was successful!

You can now convert this date object to any other string format.

Handling different separators is as easy as using them in the format string:

from datetime import datetime

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

Sonuç

In this article, we studied how to format dates in Python. We saw how the datetime module in Python can be used for the manipulation of date and time values. The module contains a number of classes that can be used for this purpose. For example, the time class is used to represent time values while the date class is used to represent calendar date values.

Zaman Damgası:

Den fazla Yığın kötüye kullanımı