Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีได้วันที่และเวลาปัจจุบันใน Python

ได้วันที่และเวลาปัจจุบันหลายวิธี วิธีง่ายสุดใช้โมดูล datetime มีฟังก์ชัน now คืน current date และ time

ตัวอย่าง

import datetime
now = datetime.datetime.now()
print("Current date and time: ")
print(str(now))

ผลลัพธ์

2017-12-29 11:24:48.042720

จัดรูปแบบวันที่เวลาด้วย strftime รับ format string ดีเรกทีฟเหมือนข้างต้น (ตารางครบถ้วน)

ตัวอย่าง

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