forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtime_conversions.py
109 lines (81 loc) · 2.2 KB
/
time_conversions.py
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
from datetime import datetime, timedelta
def seconds_to_minutes(seconds: int) -> int:
"""
Convert seconds to minutes.
Args:
seconds (int): The number of seconds.
Returns:
int: The equivalent number of minutes.
>>> seconds_to_minutes(60)
1
>>> seconds_to_minutes(300)
5
>>> seconds_to_minutes(3600)
60
"""
minutes = seconds // 60
return minutes
def minutes_to_hours(minutes: int) -> int:
"""
Convert minutes to hours.
Args:
minutes (int): The number of minutes.
Returns:
int: The equivalent number of hours.
>>> minutes_to_hours(60)
1
>>> minutes_to_hours(120)
2
>>> minutes_to_hours(180)
3
"""
hours = minutes // 60
return hours
def hours_to_days(hours: int) -> int:
"""
Convert hours to days.
Args:
hours (int): The number of hours.
Returns:
int: The equivalent number of days.
>>> hours_to_days(24)
1
>>> hours_to_days(48)
2
>>> hours_to_days(72)
3
"""
days = hours // 24
return days
def string_to_datetime(date_str: str, date_format: str = "%Y-%m-%d") -> datetime:
"""
Convert a date string to a datetime object.
Args:
date_str (str): The date string.
date_format (str, optional): The format of the date string. Default is '%Y-%m-%d'.
Returns:
datetime: The datetime object.
>>> date_str = "2023-10-15"
>>> date_obj = string_to_datetime(date_str)
>>> date_obj.strftime('%Y-%m-%d')
'2023-10-15'
"""
date_obj = datetime.strptime(date_str, date_format)
return date_obj
def datetime_to_string(date_obj: datetime, date_format: str = "%d/%m/%Y") -> str:
"""
Convert a datetime object to a date string.
Args:
date_obj (datetime): The datetime object.
date_format (str, optional): The desired format of the date string. Default is '%d/%m/%Y'.
Returns:
str: The date string.
>>> date_obj = datetime(2023, 10, 15)
>>> datetime_to_string(date_obj)
'15/10/2023'
"""
date_string = date_obj.strftime(date_format)
return date_string
if __name__ == "__main__":
import doctest
doctest.testmod()