English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在本文中,您将学习如何将date、time和datetime对象转换为它的等效字符串(通过示例)
strftime()方法使用date,time或datetime对象返回表示日期和时间的字符串。
下面的程序将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.
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.
Importamos la clase de módulo datetime. Porque los objetos de la clase datetime pueden acceder al método strftime().
El objeto datetime que contiene la fecha y hora actual se almacena ennowen
El método strftime() se puede usar para crear cadenas formateadas.
La cadena que pasa al método strftime() puede contener varios códigos de formato.
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
La siguiente tabla muestra todos los códigos que puede pasar al método strftime().
Instrucción | Significado | Por ejemplo |
%a | Abreviatura del nombre del día laborable. | Sun, Mon, ... |
%A | Nombre completo del día laborable. | Sunday, Monday, .. |
%w | Día laborable representado en número decimal. | 0,1, ... ,6 |
%d | Día del mes, representado como número decimal rellenado con ceros. | 01, 02, ... ,31 |
%-d | Día del mes representado en número decimal. | 1,2, ... ,30 |
%b | Abreviatura del mes. | Jan, Feb, ..., Dec |
%B | Nombre completo del mes. | January, February, ... |
%m | Mes, número decimal rellenado con ceros. | 01, 02, ... ,12 |
%-m | Mes representado en número decimal. | 1,2, ... ,12 |
%y | Año sin siglo, número decimal rellenado con ceros. | 00, 01, ... ,99 |
%-y | Año sin siglo, representado en formato decimal. | 0,1, ... ,99 |
%Y | Año en formato decimal representando el siglo. | 2013,2019Y |
%H | Hour (24Horario de 24 horas), número decimal con relleno de ceros. | 00, 01, ... ,23 |
%-H | Hour (24(hour system) as a decimal number. | 0,1, ... ,23 |
%I | Hour (12Horario de 24 horas), número decimal rellenado con ceros. | 01, 02, ... ,12 |
%-I | Hour (12(hour system) as a decimal number. | 1 2 2 |
%p | Appropriate AM or PM in the language environment. | AM, PM |
%M | Minute, a zero-padded decimal number. | 00, 01, ... ,59 |
%-M | Represented by a decimal number. | 0,1, ... ,59 |
%S | The second zero-padded decimal number. | 00, 01, ... ,59 |
%-S | The second decimal digit. | 0,1, ... ,59 |
%f | Microseconds, a decimal number, padded with zeros on the left. | 000000-999999 |
%z | UTC offset, formatted as+ HHMM or-HHMM. | |
%Z | Time zone name. | |
%j | The day of the year, represented by a zero-padded decimal number. | 001, 002, ... ,366 |
%-j | The day of the year, represented by a decimal number. | 1,2, ... ,366 |
%U | The 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 |
%W | The 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 |
%c | Appropriate date and time representation in the language environment. | Mon Sep 30 07: 06: 05 2019 |
%x | Appropriate date representation in the language environment. | 13/9/30 |
%X | Appropriate time representation in the language environment. | 07: 06: 05 |
%% | The character '%%'. | % |
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.