ได้วันที่และเวลาปัจจุบันหลายวิธี วิธีง่ายที่สุดใช้โมดูล datetime มีฟังก์ชัน now() ให้วันที่และเวลาปัจจุบัน
ตัวอย่าง
import datetime
now = datetime.datetime.now()
print("Current date and time: ")
print(str(now))
ผลลัพธ์
2017-12-29 11:24:48.042720
จัดรูปแบบวันที่และเวลาได้ด้วย strftime ฟังก์ชันรับ format string สำหรับ output ที่ต้องการ directives ที่รองรับ
| Directive | Meaning |
|---|---|
| %a | Abbreviated weekday name |
| %A | Full weekday name |
| %b | Abbreviated month name |
| %B | Full month name |
| %c | Appropriate date and time representation |
| %d | Day of month [01,31] |
| %H | Hour (24-hour) [00,23] |
| %I | Hour (12-hour) [01,12] |
| %j | Day of year [001,366] |
| %m | Month [01,12] |
| %M | Minute [00,59] |
| %p | AM/PM |
| %S | Second [00,61] |
| %U | Week number (Sunday first) [00,53] |
| %w | Weekday [0(Sunday),6] |
| %W | Week number (Monday first) [00,53] |
| %x | Appropriate date representation |
| %X | Appropriate time representation |
| %y | Year without century [00,99] |
| %Y | Year with century |
| %Z | Time zone name |
| %% | Literal "%" character |
ตัวอย่าง
import datetime
now = datetime.datetime.now()
print("Current date and time: ")
print(now.strftime('%Y-%m-%d %H:%M:%S'))
print(now.strftime('%H:%M:%S on %A, %B the %dth, %Y'))
ผลลัพธ์
2017-12-29 12:19:13 12:19:13 on Friday, December the 29th, 2017