## Datetime Module
Commonly used datetime classes:
- datetime.datetime: Date and time
- datetime.date: Date
- datetime.time: Time
- datetime.timedelta: Time difference or elapsed time
```python
import datetime # from datetime import datetime/date/time/timedelta
```
### 01. `datetime` object
#### get current date and time
```python
dt_now = datetime.datetime.now()
print(dt_now)
```
2023-06-23 00:58:12.989854
```python
print(type(dt_now))
```
<class 'datetime.datetime'>
#### some attribute
```python
print(dt_now.year)
print(dt_now.month)
print(dt_now.day)
```
2023
6
23
#### create `datetime` object
```python
dt = datetime.datetime(2023, 6, 22, 12, 34, 56)
print(dt)
```
2023-06-22 12:34:56
```python
dt = datetime.datetime(2023, 6, 22)
print(dt)
```
2023-06-22 00:00:00
#### create `date` and `time` objects from `datetime` object
```python
dt = datetime.datetime(2023, 6, 22, 12, 34, 56)
d = dt.date()
print(d)
```
2023-06-22
```python
t = dt.time()
print(t)
```
12:34:56
#### create `datetime` object from `date` and `time` objects
- use `datetime.combine()`
```python
print(d)
```
2023-06-22
```python
print(t)
```
12:34:56
```python
print(datetime.datetime.combine(d, t))
```
2023-06-22 12:34:56
### 02. `date` object
#### get today's date
```python
today = datetime.date.today()
print(today)
```
2023-06-23
```python
print(type(today))
```
<class 'datetime.date'>
#### some attributes
```python
print(today.year)
print(today.month)
print(today.day)
```
2023
6
23
#### create a `date` object
```python
d = datetime.date(2023, 6, 22)
print(d)
```
2023-06-22
### 03. `time` object
#### get today's date:
As of Python 3.11, there is no direct method for creating a time object representing the current time. You can use `datetime.now()` to create a datetime object for the current date and time, and then convert it to a time object with the `time()` method.
```python
time = datetime.datetime.now().time()
print(time)
```
00:58:13.211853
```python
print(type(time))
```
<class 'datetime.time'>
#### some attributes
```python
print(time.microsecond)
print(time.second)
print(time.minute)
print(time.hour)
```
211853
13
58
0
#### create a `time` object
```python
print(datetime.time(20, 15, 30, 2000))
```
20:15:30.002000
### 04. `timedelta` object
#### generate `timedelta` object by subtracting `datetime` and `date` objects
```python
dt1 = datetime.datetime(2023, 4, 1, 20, 15, 30, 2000)
dt2 = datetime.datetime(2023, 7, 1, 10, 45, 15, 100)
td = dt2 - dt1
print(td)
# 90 days, 14:29:44.998100
print(type(td))
# <class 'datetime.timedelta'>
print(td.days)
# 90
print(td.seconds)
# 52184
print(td.microseconds)
# 998100
print(td.total_seconds())
# 7828184.9981
```
90 days, 14:29:44.998100
<class 'datetime.timedelta'>
90
52184
998100
7828184.9981
#### arithmetic with `timedelta` objects
```python
dt = datetime.datetime(2023, 4, 1, 20, 15, 30, 2000)
print(dt)
# 2023-04-01 20:15:30.002000
print(dt - datetime.timedelta(weeks=1))
# 2023-03-25 20:15:30.002000
print(dt + datetime.timedelta(days=10))
# 2023-04-11 20:15:30.002000
print(dt + datetime.timedelta(minutes=50))
# 2023-04-01 21:05:30.002000
# calculate date interval:
d_target = datetime.date(2023, 5, 1)
td = d_target - dt.date()
print(td)
```
2023-04-01 20:15:30.002000
2023-03-25 20:15:30.002000
2023-04-11 20:15:30.002000
2023-04-01 21:05:30.002000
30 days, 0:00:00
### 05. `strftime()`
- convert date and time to a string
- here are the format codes commonly used:
```
%d: Day of the month as a zero-padded decimal number
%m: Month as a zero-padded decimal number
%y: Year without century as a zero-padded decimal number
%Y: Year with century as a decimal number
%H: Hour (24-hour clock) as a zero-padded decimal number
%I: Hour (12-hour clock) as a zero-padded decimal number
%M: Minute as a zero-padded decimal number
%S: Second as a zero-padded decimal number
%f: Microsecond as a decimal number, zero-padded to 6 digits
%A: Weekday as locale’s full name
%a: Weekday as locale’s abbreviated name
%B: Month as locale’s full name
%b: Month as locale’s abbreviated name
%j: Day of the year as a zero-padded decimal number
%U: Week number of the year (Sunday as the first day of the week) as a zero-padded decimal number
%W: Week number of the year (Monday as the first day of the week) as a zero-padded decimal number
```
```python
dt = datetime.datetime(2023, 5, 30, 20, 15, 30, 2000)
print(dt.strftime('%Y/%m/%d %H:%M:%S.%f'))
```
2023/05/30 20:15:30.002000
```python
print(dt.strftime('%A, %B %d, %Y'))
```
Tuesday, May 30, 2023
```python
d = dt.date()
print(d.strftime('%Y/%m/%d %H:%M:%S.%f'))
```
2023/05/30 00:00:00.000000
```python
t = dt.time()
print(t.strftime('%Y/%m/%d %H:%M:%S.%f'))
```
1900/01/01 20:15:30.002000
### 06. `strptime()`
- string parsed time
- convert strings to date and time
```python
s = '2023/6/12 20:30'
s_format = '%Y/%m/%d %H:%M'
dt = datetime.datetime.strptime(s, s_format)
print(dt)
```
2023-06-12 20:30:00
#### convert to another string by using `strftime()`
```python
print(dt)
new_dt = dt.strftime("%Y%m%d_%H%M%S")
print(new_dt)
```
2023-06-12 20:30:00
20230612_203000
### 07. ISO 8601 format of time:
- convert datetime to isoformat: `isoformat()`
- convert isoformat string to datetime: `fromisoformat()`
```python
dt = datetime.datetime.now()
print(type(dt))
```
<class 'datetime.datetime'>
```python
print(dt.isoformat())
print(type(dt.isoformat()))
```
2023-06-23T00:58:13.398855
<class 'str'>
```python
iso_string = "2023-06-22T05:00:30.001000"
dt = datetime.datetime.fromisoformat(iso_string)
print(dt)
print(type(dt))
```
2023-06-22 05:00:30.001000
<class 'datetime.datetime'>
### 08. UNIX time:
```
Unix time is the number of seconds that have elapsed since the Unix epoch, 00:00:00 UTC (Coordinated Universal Time) on January 1, 1970. It is also known as Epoch time, Posix time, and so on.
```
- convert datetime to isoformat: `timestamp()`
- convert isoformat string to datetime: `fromtimestamp()`
```python
dt = datetime.datetime.now()
print(type(dt))
# how many seconds have been since 1970/01/01 09:00:00 until now
ts = dt.timestamp()
print(ts)
print(type(ts))
```
<class 'datetime.datetime'>
1687449493.447855
<class 'float'>
```python
dt = datetime.datetime.fromtimestamp(0)
print(dt)
print(type(dt))
```
1970-01-01 09:00:00
<class 'datetime.datetime'>
```python
dt = datetime.datetime.fromtimestamp(ts)
print(dt)
```
2023-06-23 00:58:13.447855
### 09. Case Study:
#### inuput: datetime str in ISO 8601 format; output: yesterday(in datetime format)
```python
def get_yesterday(x: str):
d = datetime.datetime.fromisoformat(x)
td = datetime.timedelta(days=1)
return d - td
```
```python
print(get_yesterday("2022-01-02"))
```
2022-01-01 00:00:00
#### inuput: datetime str in ISO 8601 format; output:ISO 8601 in %Y-%m-%d %H:%M:%S
```python
def isotime_convert(x: str):
d = datetime.datetime.strptime(x, "%a %b %d %y %H:%M:%S")
time_string = d.strftime("%Y-%m-%d %H:%M:%S")
return time_string
```
```python
isotime_convert("Fri Dec 31 21 23:59:59")
```
'2021-12-31 23:59:59'