English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python 基础教程

Python 流程控制

Funciones en Python

Tipos de datos en Python

Python 文件操作

Python 对象和类

Python 日期和时间

Python 高级知识

Python 参考手册

strftime() en Python

在本文中,您将学习如何将date、time和datetime对象转换为它的等效字符串(通过示例)

strftime()方法使用date,timedatetime对象返回表示日期和时间的字符串。

Example1:使用strftime()将日期时间转换为字符串

下面的程序将datetime包含当前日期和时间的对象转换  为不同格式的字符串。

from datetime import datetime
now = datetime.now() # 当前的日期和时间
year = now.strftime("%Y")
print("年:", year)
month = now.strftime("%m")
print("月:", month)
day = now.strftime("%d")
print("日:", day)
time = now.strftime("%H:%M:%S")
print("时间:", time)
date_time = now.strftime("%m/%d/d = date_time.strftime("%Y, %H:%M:%S")
print("Fecha y hora:", date_time)

Cuando ejecuta el programa, la salida será como sigue:

Año: 2020
Mes: 04
Día: 13
Hora: 17:35:22
Fecha y hora: 04/13/2020, 17:35:22

Aquí,year,day,timeydate_timees una cadena, mientras quenowes un objeto datetime.

¿Cómo funciona strftime()?

En el programa anterior, %Y, %m, %d, etc. son códigos de formato. El método strftime() toma uno o más códigos de formato como parámetros y devuelve una cadena formateada basada en esos parámetros.

  1. Importamos la clase de módulo datetime. Porque los objetos de la clase datetime pueden acceder al método strftime().

     

  2. El objeto datetime que contiene la fecha y hora actual se almacena ennowen

     

  3. El método strftime() se puede usar para crear cadenas formateadas.

     

  4. La cadena que pasa al método strftime() puede contener varios códigos de formato.

     

Example2:Crear una cadena a partir de la marca de tiempo

from datetime import datetime
timestamp = 1578797322
date_time = datetime.fromtimestamp(timestamp)
print("Objeto de fecha y hora:", date_time)
d = date_time.strftime("%m/%d/d = date_time.strftime("%Y, %H:%M:%S")
print("Output 2: "	
d = date_time.strftime("%d %b, %Y")
print("Output 3: "
d = date_time.strftime("%d %B, %Y")
print("Output 4: "
d = date_time.strftime("%I%p")
print("Output 5: "

When running the program, the output is:

Objeto de fecha y hora: 2020-01-12 10:48:42
Output 2: 01/12/2020, 10:48:42
Output 3: 12 Jan, 2020
Output 4: 12 January, 2020
Output 5: 10AM

Lista de códigos de formato

La siguiente tabla muestra todos los códigos que puede pasar al método strftime().

InstrucciónSignificadoPor ejemplo
%aAbreviatura del nombre del día laborable.Sun, Mon, ...
%ANombre completo del día laborable.Sunday, Monday, ..
%wDía laborable representado en número decimal.0,1, ... ,6
%dDía del mes, representado como número decimal rellenado con ceros.01, 02, ... ,31
%-dDía del mes representado en número decimal.1,2, ... ,30
%bAbreviatura del mes.Jan, Feb, ..., Dec
%BNombre completo del mes.January, February, ...
%mMes, número decimal rellenado con ceros.01, 02, ... ,12
%-mMes representado en número decimal.1,2, ... ,12
%yAño sin siglo, número decimal rellenado con ceros.00, 01, ... ,99
%-yAño sin siglo, representado en formato decimal.0,1, ... ,99
%YAño en formato decimal representando el siglo.2013,2019Y
%HHour (24Horario de 24 horas), número decimal con relleno de ceros.00, 01, ... ,23
%-HHour (24(hour system) as a decimal number.0,1, ... ,23
%IHour (12Horario de 24 horas), número decimal rellenado con ceros.01, 02, ... ,12
%-IHour (12(hour system) as a decimal number.1 2 2
%pAppropriate AM or PM in the language environment.AM, PM
%MMinute, a zero-padded decimal number.00, 01, ... ,59
%-MRepresented by a decimal number.0,1, ... ,59
%SThe second zero-padded decimal number.00, 01, ... ,59
%-SThe second decimal digit.0,1, ... ,59
%fMicroseconds, a decimal number, padded with zeros on the left.000000-999999
%zUTC offset, formatted as+ HHMM or-HHMM. 
%ZTime zone name. 
%jThe day of the year, represented by a zero-padded decimal number.001, 002, ... ,366
%-jThe day of the year, represented by a decimal number.1,2, ... ,366
%UThe week number of the year (Sunday is the first day of the week). All days before the first Sunday of a new year are considered to be in the 0th week.00, 01, ... ,53
%WThe week number of the year (Monday is the first day of the week). All days before the first Monday of a new year are considered to be in the 0th week.00, 01, ... ,53
%cAppropriate date and time representation in the language environment.Mon Sep 30 07: 06: 05 2019
%xAppropriate date representation in the language environment.13/9/30
%XAppropriate time representation in the language environment.07: 06: 05
%%The character '%%'.%

Example3: Appropriate date and time in the language environment

from datetime import datetime
timestamp = 1578797322
date_time = datetime.fromtimestamp(timestamp)
d = date_time.strftime("%c")
print("Output 1: "	
d = date_time.strftime("%x")
print("Output 2: "
d = date_time.strftime("%X")
print("Output 3: "

When running the program, the output is:

Output 1: Sun Jan 12 10:48:42 2020
Output 2: 01/12/20
Output 3: 10:48:42

Format codes %c, %x, and %X are used for appropriate date and time representations in the language environment.

We also recommend that you checkstrptime() en PythonThe strptime() method creates a datetime object from a string.