forked from midudev/curso-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01_dates.py
More file actions
56 lines (34 loc) · 1.23 KB
/
01_dates.py
File metadata and controls
56 lines (34 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# Trabajando con fechas y horas en Python
from datetime import datetime, timedelta
import locale
# 1. Obtener la fecha y hora actual
now = datetime.now()
print(f"Fecha y hora actual: {now}")
# 2. Crear una fecha y hora específica
specific_date = datetime(2025, 2, 12, 15, 30, 0)
print(f"Fecha y hora específica: {specific_date}")
# 3. Formatear fechas
# método strftime() para formatear fechas
# pasarle el objeto datetime y el formato especificado
# formato:
import locale
locale.setlocale(locale.LC_TIME, 'es_ES.UTF-8')
format_date = now.strftime("%A %B %Y %H:%M:%S")
print(f"Fecha formateada: {format_date}")
# 4. Operaciones con fechas (sumar/restar dias, minutos, horas, meses)
yesterday = datetime.now() - timedelta(days=1)
print(f"Ayer: {yesterday}")
tomorrow = datetime.now() + timedelta(days=1)
print(f"Mañana: {tomorrow}")
one_hour_after = datetime.now() + timedelta(hours=1)
print(f"Una hora después: {one_hour_after}")
# 5. Obtener componentes individuales de una fecha
year = now.year
print(year)
month = now.month
print(month)
# 6. Calcular la diferencia entre 2 fechas
date1 = datetime.now()
date2 = datetime(2025, 2, 12, 15, 30, 0)
difference = date2 - date1
print(f"Diferencia entre las fechas: {difference}")