SIGN IN SIGN UP

The 30 Days of Python programming challenge is a step-by-step guide to learn the Python programming language in 30 days. This challenge may take more than 100 days. Follow your own pace. These videos may help too: https://www.youtube.com/channel/UC7PNRuno1rzYPb1xLa4yktw

60083 0 1 Python
2020-04-29 09:44:05 +03:00
<div align="center">
<h1> 30 Days Of Python: Day 16 - Python Date time </h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Author:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
2021-07-08 06:21:26 +03:00
<small>Second Edition: July, 2021</small>
2020-04-29 09:44:05 +03:00
</sub>
</div>
2020-07-09 13:37:48 +03:00
[<< Day 15](../15_Day_Python_type_errors/15_python_type_errors.md) | [Day 17 >>](../17_Day_Exception_handling/17_exception_handling.md)
2020-04-29 09:44:05 +03:00
![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png)
2020-07-09 13:37:48 +03:00
- [📘 Day 16](#-day-16)
2020-05-16 09:35:49 +03:00
- [Python *datetime*](#python-datetime)
2020-05-16 09:42:53 +03:00
- [Getting *datetime* Information](#getting-datetime-information)
2021-07-08 06:21:26 +03:00
- [Formatting Date Output Using *strftime*](#formatting-date-output-using-strftime)
2020-05-16 09:42:53 +03:00
- [String to Time Using *strptime*](#string-to-time-using-strptime)
- [Using *date* from *datetime*](#using-date-from-datetime)
2020-05-16 10:01:40 +03:00
- [Time Objects to Represent Time](#time-objects-to-represent-time)
2020-07-09 13:37:48 +03:00
- [Difference Between Two Points in Time Using](#difference-between-two-points-in-time-using)
2024-10-09 11:40:24 +03:00
- [Difference Between Two Points in Time Using *timedelta*](#difference-between-two-points-in-time-using-timedelta)
2020-07-09 13:37:48 +03:00
- [💻 Exercises: Day 16](#-exercises-day-16)
2020-04-29 09:44:05 +03:00
# 📘 Day 16
2020-05-16 09:35:49 +03:00
## Python *datetime*
2020-04-29 09:44:05 +03:00
2020-05-16 10:01:40 +03:00
Python has got _datetime_ module to handle date and time.
2020-04-29 09:44:05 +03:00
```py
import datetime
print(dir(datetime))
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo']
```
2021-07-08 06:21:26 +03:00
With dir or help built-in commands it is possible to know the available functions in a certain module. As you can see, in the datetime module there are many functions, but we will focus on _date_, _datetime_, _time_ and _timedelta_. Let se see them one by one.
2020-04-29 09:44:05 +03:00
2020-05-16 10:01:40 +03:00
### Getting *datetime* Information
2020-04-29 09:44:05 +03:00
```py
from datetime import datetime
now = datetime.now()
2021-07-08 06:21:26 +03:00
print(now) # 2021-07-08 07:34:46.549883
day = now.day # 8
month = now.month # 7
year = now.year # 2021
hour = now.hour # 7
2020-04-29 09:44:05 +03:00
minute = now.minute # 38
second = now.second
timestamp = now.timestamp()
print(day, month, year, hour, minute)
print('timestamp', timestamp)
2021-07-08 06:21:26 +03:00
print(f'{day}/{month}/{year}, {hour}:{minute}') # 8/7/2021, 7:38
2020-04-29 09:44:05 +03:00
```
2020-05-16 10:01:40 +03:00
Timestamp or Unix timestamp is the number of seconds elapsed from 1st of January 1970 UTC.
2021-07-08 06:21:26 +03:00
### Formatting Date Output Using *strftime*
2020-04-29 09:44:05 +03:00
```py
from datetime import datetime
new_year = datetime(2020, 1, 1)
print(new_year) # 2020-01-01 00:00:00
day = new_year.day
month = new_year.month
year = new_year.year
hour = new_year.hour
minute = new_year.minute
second = new_year.second
print(day, month, year, hour, minute) #1 1 2020 0 0
print(f'{day}/{month}/{year}, {hour}:{minute}') # 1/1/2020, 0:0
```
2021-07-08 06:21:26 +03:00
Formatting date time using *strftime* method and the documentation can be found [here](https://strftime.org/).
2020-04-29 09:44:05 +03:00
```py
from datetime import datetime
# current date and time
now = datetime.now()
t = now.strftime("%H:%M:%S")
print("time:", t) # time: 18:21:40
2020-04-29 09:44:05 +03:00
time_one = now.strftime("%m/%d/%Y, %H:%M:%S")
# mm/dd/YY H:M:S format
print("time one:", time_one) # time one: 06/28/2022, 18:21:40
2020-04-29 09:44:05 +03:00
time_two = now.strftime("%d/%m/%Y, %H:%M:%S")
# dd/mm/YY H:M:S format
print("time two:", time_two) # time two: 28/06/2022, 18:21:40
2020-04-29 09:44:05 +03:00
```
```sh
time: 01:05:01
time one: 12/05/2019, 01:05:01
time two: 05/12/2019, 01:05:01
```
2020-05-16 10:01:40 +03:00
Here are all the _strftime_ symbols we use to format time. An example of all the formats for this module.
2020-04-29 09:44:05 +03:00
2021-07-08 06:21:26 +03:00
![strftime](../images/strftime.png)
2020-04-29 09:44:05 +03:00
2020-05-16 09:42:53 +03:00
### String to Time Using *strptime*
2024-02-14 09:39:32 +01:00
Here is a [documentation](https://www.programiz.com/python-programming/datetime/strptime) hat helps to understand the format.
2020-04-29 09:44:05 +03:00
```py
from datetime import datetime
date_string = "5 December, 2019"
print("date_string =", date_string) # date_string = 5 December, 2019
2020-04-29 09:44:05 +03:00
date_object = datetime.strptime(date_string, "%d %B, %Y")
print("date_object =", date_object) # date_object = 2019-12-05 00:00:00
2020-04-29 09:44:05 +03:00
```
```sh
date_string = 5 December, 2019
date_object = 2019-12-05 00:00:00
```
2020-05-16 09:42:53 +03:00
### Using *date* from *datetime*
2020-04-29 09:44:05 +03:00
```py
from datetime import date
d = date(2020, 1, 1)
print(d) # 2020-01-01
2020-04-29 09:44:05 +03:00
print('Current date:', d.today()) # 2019-12-05
# date object of today's date
today = date.today()
print("Current year:", today.year) # 2019
print("Current month:", today.month) # 12
print("Current day:", today.day) # 5
```
2020-05-16 10:01:40 +03:00
### Time Objects to Represent Time
2020-04-29 09:44:05 +03:00
```py
from datetime import time
# time(hour = 0, minute = 0, second = 0)
a = time()
print("a =", a) # a = 00:00:00
2020-04-29 09:44:05 +03:00
# time(hour, minute and second)
b = time(10, 30, 50)
print("b =", b) # b = 10:30:50
2020-04-29 09:44:05 +03:00
# time(hour, minute and second)
c = time(hour=10, minute=30, second=50)
print("c =", c) # c = 10:30:50
2020-04-29 09:44:05 +03:00
# time(hour, minute, second, microsecond)
d = time(10, 30, 50, 200555)
print("d =", d) # d = 10:30:50.200555
2020-04-29 09:44:05 +03:00
```
output
a = 00:00:00
b = 10:30:50
c = 10:30:50
d = 10:30:50.200555
2020-05-16 10:01:40 +03:00
### Difference Between Two Points in Time Using
2020-04-29 09:44:05 +03:00
```py
2023-09-18 23:29:32 -07:00
from datetime import date, datetime
2020-04-29 09:44:05 +03:00
today = date(year=2019, month=12, day=5)
new_year = date(year=2020, month=1, day=1)
time_left_for_newyear = new_year - today
# Time left for new year: 27 days, 0:00:00
print('Time left for new year: ', time_left_for_newyear) # Time left for new year: 27 days, 0:00:00
2020-04-29 09:44:05 +03:00
t1 = datetime(year = 2019, month = 12, day = 5, hour = 0, minute = 59, second = 0)
t2 = datetime(year = 2020, month = 1, day = 1, hour = 0, minute = 0, second = 0)
diff = t2 - t1
print('Time left for new year:', diff) # Time left for new year: 26 days, 23: 01: 00
```
2024-10-09 11:40:24 +03:00
### Difference Between Two Points in Time Using *timedelta*
2020-04-29 09:44:05 +03:00
```py
from datetime import timedelta
t1 = timedelta(weeks=12, days=10, hours=4, seconds=20)
t2 = timedelta(days=7, hours=5, minutes=3, seconds=30)
t3 = t1 - t2
print("t3 =", t3)
```
```sh
date_string = 5 December, 2019
date_object = 2019-12-05 00:00:00
t3 = 86 days, 22:56:50
```
2021-07-08 06:21:26 +03:00
🌕 You are an extraordinary. You are 16 steps a head to your way to greatness. Now do some exercises for your brain and muscles.
2020-07-09 13:37:48 +03:00
2020-04-29 09:44:05 +03:00
## 💻 Exercises: Day 16
2020-05-16 10:01:40 +03:00
1. Get the current day, month, year, hour, minute and timestamp from datetime module
2. Format the current date using this format: "%m/%d/%Y, %H:%M:%S")
3. Today is 5 December, 2019. Change this time string to time.
4. Calculate the time difference between now and new year.
5. Calculate the time difference between 1 January 1970 and now.
6. Think, what can you use the datetime module for? Examples:
2020-04-29 09:44:05 +03:00
- Time series analysis
2020-05-16 10:01:40 +03:00
- To get a timestamp of any activities in an application
- Adding posts on a blog
2020-04-29 09:44:05 +03:00
🎉 CONGRATULATIONS ! 🎉
2024-02-14 09:39:32 +01:00
[<< Day 15](../15_Day_Python_type_errors/15_python_type_errors.md) | [Day 17 >>](../17_Day_Exception_handling/17_exception_handling.md)