Skip to content

Commit 4ee5b32

Browse files
Create dates_and_times.md
Added content for Working with dates & times in python
1 parent 406004d commit 4ee5b32

File tree

1 file changed

+129
-0
lines changed

1 file changed

+129
-0
lines changed
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
## Working with Dates and Times in Python
2+
Handling dates and times is an essential aspect of many programming tasks.
3+
Python provides robust modules to work with dates and times, making it easier to perform operations like formatting, parsing, and arithmetic.
4+
This guide provides an overview of these modules and their key functionalities.
5+
6+
## 1. 'datetime' Module
7+
The datetime module supplies classes for manipulating dates and times. The main classes in the datetime module are:
8+
9+
* date: Represents a date (year, month, day).
10+
* time: Represents a time (hour, minute, second, microsecond).
11+
* datetime: Combines date and time information.
12+
* timedelta: Represents the difference between two dates or times.
13+
* tzinfo: Provides time zone information objects.
14+
15+
**Key Concepts:**
16+
17+
* Naive vs. Aware: Naive datetime objects do not contain time zone information, while aware datetime objects do.
18+
* Immutability: date and time objects are immutable; once created, they cannot be changed.
19+
20+
Example:
21+
```bash
22+
python
23+
Copy code
24+
import datetime
25+
# Get the current date and time
26+
now = datetime.datetime.now()
27+
print("Current date and time:", now)
28+
```
29+
30+
## 2. Formatting Dates and Times
31+
Formatting involves converting datetime objects into human-readable strings. This is achieved using the strftime method, which stands for "string format time."
32+
You can specify various format codes to dictate how the output string should be structured.
33+
34+
**Common Format Codes:**
35+
36+
* %Y: Year with century (e.g., 2024)
37+
* %m: Month as a zero-padded decimal number (e.g., 01)
38+
* %d: Day of the month as a zero-padded decimal number (e.g., 15)
39+
* %H: Hour (24-hour clock) as a zero-padded decimal number (e.g., 13)
40+
* %M: Minute as a zero-padded decimal number (e.g., 45)
41+
* %S: Second as a zero-padded decimal number (e.g., 30)
42+
43+
Example:
44+
```bash
45+
python
46+
Copy code
47+
import datetime
48+
49+
now = datetime.datetime.now()
50+
formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")
51+
print("Formatted current date and time:", formatted_now)
52+
```
53+
54+
## 3. Parsing Dates and Times
55+
Parsing is the process of converting strings representing dates and times into datetime objects. The strptime method, which stands for "string parse time,"
56+
allows you to specify the format of the input string.
57+
58+
Example:
59+
```bash
60+
python
61+
Copy code
62+
import datetime
63+
64+
date_string = "2024-05-15 13:45:30"
65+
date_object = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
66+
print("Parsed date and time:", date_object)
67+
```
68+
69+
## 4. Working with Time Differences
70+
The timedelta class is used to represent the difference between two datetime objects. This is useful for calculations involving durations, such as finding the
71+
number of days between two dates or adding a certain period to a date.
72+
73+
Example:
74+
```bash
75+
python
76+
Copy code
77+
import datetime
78+
79+
date1 = datetime.datetime(2024, 5, 15, 12, 0, 0)
80+
date2 = datetime.datetime(2024, 5, 20, 14, 30, 0)
81+
82+
difference = date2 - date1
83+
print("Difference:", difference)
84+
print("Days:", difference.days)
85+
print("Total seconds:", difference.total_seconds())
86+
```
87+
88+
## 5. Time Zones
89+
Time zone handling in Python is facilitated by the pytz library. It allows you to convert naive datetime objects into timezone-aware objects and perform
90+
operations across different time zones.
91+
92+
**Key Concepts:**
93+
94+
* Timezone-aware: A datetime object that includes timezone information.
95+
* Localization: The process of associating a naive datetime with a time zone.
96+
97+
Example:
98+
```bash
99+
python
100+
Copy code
101+
import datetime
102+
import pytz
103+
104+
# Define a timezone
105+
tz = pytz.timezone('Asia/Kolkata')
106+
107+
# Get the current time in a specific timezone
108+
now = datetime.datetime.now(tz)
109+
print("Current time in Asia/Kolkata:", now)
110+
```
111+
112+
## 6. Date Arithmetic
113+
Date arithmetic involves performing operations like addition or subtraction on date or datetime objects using timedelta. This is useful for calculating future
114+
or past dates based on a given date.
115+
116+
Example:
117+
```bash
118+
python
119+
Copy code
120+
import datetime
121+
122+
today = datetime.date.today()
123+
future_date = today + datetime.timedelta(days=10)
124+
print("Date after 10 days:", future_date)
125+
```
126+
127+
## Summary
128+
Python’s datetime module and the pytz library provide comprehensive tools for working with dates, times, and time zones. They enable you to perform a wide range
129+
of operations, from basic date manipulations to complex time zone conversions.

0 commit comments

Comments
 (0)