Python DateTime

datetime.date

from datetime import date
today = date.today()

print(type(today))
# <class 'datetime.date'>
print(today)
# 2022-08-19

datetime.datetime

เวลาปัจจุบันของ server

from datetime import datetime
now = datetime.now() # current date and time

print(type(now))
# <class 'datetime.datetime'>
print(now)
# 2022-08-19 07:51:55.893002

นำเวลาปัจจุบันของ server มาบวก 7 ชั่วโมง

import datetime
now = datetime.datetime.now()
print(now)
# 2022-08-19 08:32:36.803853

now = now + datetime.timedelta(hours=7)
print(now)
# 2022-08-19 15:32:36.803853
from datetime import datetime
now = datetime.now() # current date and time

year = now.strftime("%Y")
print("year:", year)
# year: 2022

month = now.strftime("%m")
print("month:", month)
# month: 08

day = now.strftime("%d")
print("day:", day)
# day: 19

time = now.strftime("%H:%M:%S")
print("time:", time)
# time: 08:12:42

date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)	
# date and time: 08/19/2022, 08:12:42

time.struct_time

from datetime import datetime
now = datetime.now() # current date and time
time_tuple = now.timetuple()

print(type(time_tuple))
# <class 'time.struct_time'>

print(now)
# 2022-08-19 07:55:03.144893

print(time_tuple)
# time.struct_time(tm_year=2022, tm_mon=8, tm_mday=19, tm_hour=7, tm_min=55, tm_sec=3, tm_wday=4, tm_yday=231, tm_isdst=-1)

timestamp

หาค่า timestamp จาก current date และ time

import time
from datetime import datetime
now = datetime.now() # current date and time
time_tuple = now.timetuple()
timestamp = int(time.mktime(time_tuple))

print(now)
# 2022-08-19 07:59:21.232243

print(timestamp)
# 1660895961

เปลี่ยน type ของข้อมูล (float, int, str, bytes)

import time
from datetime import datetime
now = datetime.now() # current date and time
time_tuple = now.timetuple()
timestamp = time.mktime(time_tuple)

print(type(timestamp))
print(timestamp)
# <class 'float'>
# 1660898887.0

timestamp = int(timestamp)
print(type(timestamp))
print(timestamp)
# <class 'int'>
# 1660898887

timestamp = str(timestamp)
print(type(timestamp))
print(timestamp)
# <class 'str'>
# 1660898887

timestamp = str.encode(timestamp)
print(type(timestamp))
print(timestamp)
# <class 'bytes'>
# b'1660898887'

timestamp = timestamp.decode()
print(type(timestamp))
print(timestamp)
# <class 'str'>
# 1660898887

หาค่า timestamp จากวันที่ ที่กำหนด

import time
from datetime import datetime

# date in string format
dt="19/08/2022"

time_tuple = datetime.strptime(dt, "%d/%m/%Y").timetuple()
print(time_tuple)
# time.struct_time(tm_year=2022, tm_mon=8, tm_mday=19, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=231, tm_isdst=-1)

timestamp = time.mktime(time_tuple)
print(timestamp)
# 1660867200.0