Convertir formato de fecha a cadena
# 根据字符串类型转日期 返回值类型<class 'time.struct_time'>
st_time = time.strptime('2019-4-30 11:32:23', '%Y-%m-%d %H:%M:%S')
print(str(st_time) + " 类型:" + str(type(st_time)))
# time.struct_time(tm_year=2019, tm_mon=4, tm_mday=30, tm_hour=11, tm_min=32, tm_sec=23, tm_wday=1, tm_yday=120, tm_isdst=-1) 类型:<class 'time.struct_time'>
# 根据<class 'time.struct_time'>日期类型转字符 返回值类型<class 'str'>
str_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
print(str_time + " 类型:" + str(type(str_time)))
# 2019-04-26 12:33:04 类型:<class 'str'>
# 获取当前日期 返回值类型<class 'time.struct_time'>
st_time = time.localtime()
print(str(st_time) + " 类型:" + str(type(st_time)))
# time.struct_time(tm_year=2019, tm_mon=4, tm_mday=26, tm_hour=12, tm_min=47, tm_sec=41, tm_wday=4, tm_yday=116, tm_isdst=0) 类型:<class 'time.struct_time'>
# 获取当前日期时间戳 返回值类型<class 'float'>
float_time = time.time()
print(str(float_time) + " 类型:" + str(type(float_time)))
# 1556254126.6432147 类型:<class 'float'>
# 根据<class 'time.struct_time'>日期类型转换为时间戳 返回值类型<class 'float'>
float_time = time.mktime(time.localtime())
print(str(float_time) + " 类型:" + str(type(float_time)))
# 1556256409.0 类型:<class 'float'>
# 根据<class 'float'>日期戳转换为struct_time日期 返回值类型<class 'time.struct_time'>
st_time = time.localtime(time.time())
print(str(st_time) + " 类型:" + str(type(st_time)))
# time.struct_time(tm_year=2019, tm_mon=4, tm_mday=26, tm_hour=15, tm_min=5, tm_sec=48, tm_wday=4, tm_yday=116, tm_isdst=0) 类型:<class 'time.struct_time'>
Cálculo de hora y fecha.
Recomiendo encarecidamente parientedelta
El tipo de relación relativa está diseñado para aplicarse a una fecha y hora existente y puede reemplazar componentes específicos de esa fecha y hora o representar intervalos de tiempo.
Fácil de usar:
- Hay dos formas diferentes de construir una instancia derelativadelta. El primero es pasar dos clases de fecha/fechahora:
eg:relativedelta(datetime1, datetime2)
- El segundo es pasar cualquier número de los siguientes argumentos de palabras clave:
relativedelta(arg1=x,arg2=y,arg3=z...)
year, month, day, hour, minute, second, microsecond:
Absolute information (argument is singular); adding or subtracting a
relativedelta with absolute information does not perform an arithmetic
operation, but rather REPLACES the corresponding value in the
original datetime with the value(s) in relativedelta.
years, months, weeks, days, hours, minutes, seconds, microseconds:
Relative information, may be negative (argument is plural); adding
or subtracting a relativedelta with relative information performs
the corresponding arithmetic operation on the original datetime value
with the information in the relativedelta.
weekday:
One of the weekday instances (MO, TU, etc) available in the
relativedelta module. These instances may receive a parameter N,
specifying the Nth weekday, which could be positive or negative
(like MO(+1) or MO(-2)). Not specifying it is the same as specifying
+1. You can also use an integer, where 0=MO. This argument is always
relative e.g. if the calculated date is already Monday, using MO(1)
or MO(-1) won't change the day. To effectively make it absolute, use
it in combination with the day argument (e.g. day=1, MO(1) for first
Monday of the month).
leapdays:
Will add given days to the date found, if year is a leap
year, and the date found is post 28 of february.
yearday, nlyearday:
Set the yearday or the non-leap year day (jump leap days).
These are converted to day/month/leapdays information.
Los argumentos de palabras clave tienen formas relativas y absolutas. El plural es relativo y el singular es absoluto. Para cada parámetro en el siguiente orden, primero se aplica la forma absoluta (al establecer cada propiedad en ese valor) y luego se aplica la forma relativa (al agregar el valor a la propiedad).
El orden de las propiedades consideradas cuando se agrega este delta relativo a una fecha y hora es:
Año
Mes
Día
Hora
Minuto
Segundo
Microsegundo
Finalmente, el día de la semana se aplica usando las reglas anteriores.
Por ejemplo:
>>> from datetime import datetime
>>> from dateutil.relativedelta import relativedelta, MO
>>> dt = datetime(2018, 4, 9, 13, 37, 0)
>>> delta = relativedelta(hours=25, day=1, weekday=MO(1))
>>> dt + delta
datetime.datetime(2018, 4, 2, 14, 37)
使用示例:
date_end = date_start.date() + relativedelta(months=3, days=-1)
Devuelve un objeto dateutil.relativedelta.relativedelta.
timedelta es un objeto en datetime que representa la diferencia entre dos tiempos
Constructor: datetime.timedelta(días=0, segundos=0, microsegundos=0, milisegundos=0, minutos=0, horas=0, semanas=0) donde los parámetros son opcionales y el valor predeterminado es 0
donde
:
1 milisegundo = 1000 microsegundos
1 minuto = 60 segundos
1 hora = 3600 segundos
1 semana = 7 días
En el constructor, preste atención al rango de valores de los parámetros:
0 <= microsegundos < 1000000
0 <= segundos < 3600*24 (la cantidad de segundos en un día)
-999999999 <= días <= 999999999
import datetime
nowtime=datetime.datetime.now()
print(nowtime.strftime('%Y-%m-%d %H:%M:%S'))
delta=datetime.timedelta(days=1)
rs=nowtime+delta
print(rs.strftime('%Y-%m-%d %H:%M:%S'))