Fecha y hora año y mes actual en Python

Resuelto user3778327 asked hace 9 años • 10 respuestas

Debo tener el año y mes actuales en fecha y hora.

Yo uso esto:

datem = datetime.today().strftime("%Y-%m")
datem = datetime.strptime(datem, "%Y-%m")

¿Existe tal vez otra manera?

user3778327 avatar Jan 28 '15 17:01 user3778327
Aceptado

Pruebe esta solución:

from datetime import datetime

current_second = datetime.now().second
current_minute = datetime.now().minute
current_hour = datetime.now().hour

current_day = datetime.now().day
current_month = datetime.now().month
current_year = datetime.now().year
Gaurav Dave avatar Jan 28 '2015 10:01 Gaurav Dave

Usar:

from datetime import datetime
today = datetime.today()
datem = datetime(today.year, today.month, 1)

Supongo que quieres el primero del mes.

llogiq avatar Jan 28 '2015 10:01 llogiq

Usar:

from datetime import datetime

current_month = datetime.now().strftime('%m') # 02 This is 0 padded
current_month_text = datetime.now().strftime('%h') # Feb
current_month_text = datetime.now().strftime('%B') # February

current_day = datetime.now().strftime('%d')   # 23 This is also padded
current_day_text = datetime.now().strftime('%a')  # Fri
current_day_full_text = datetime.now().strftime('%A')  # Friday

current_weekday_day_of_today = datetime.now().strftime('%w') # 5  Where 0 is Sunday and 6 is Saturday.

current_year_full = datetime.now().strftime('%Y')  # 2018
current_year_short = datetime.now().strftime('%y')  # 18 without century

current_second= datetime.now().strftime('%S') # 53
current_minute = datetime.now().strftime('%M') # 38
current_hour = datetime.now().strftime('%H') # 16 like 4pm
current_hour = datetime.now().strftime('%I') # 04 pm

current_hour_am_pm = datetime.now().strftime('%p') # 4 pm

current_microseconds = datetime.now().strftime('%f') # 623596 Rarely we need.

current_timzone = datetime.now().strftime('%Z') # UTC, EST, CST etc. (empty string if the object is naive).

Referencia: 8.1.7. Comportamiento de strftime() y strptime()

Referencia: comportamiento de strftime() y strptime()

Lo anterior es útil para cualquier análisis de fechas, no solo ahora o hoy. Puede resultar útil para cualquier análisis de fechas.

p.ej

my_date = "23-02-2018 00:00:00"

datetime.strptime(str(my_date),'%d-%m-%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S+00:00')

datetime.strptime(str(my_date),'%d-%m-%Y %H:%M:%S').strftime('%m')

Etcétera...

Anup Yadav avatar Feb 23 '2018 11:02 Anup Yadav