สร้างรูปแบบ ISO ด้วย strftime()
ในบทที่แล้ว คุณใช้ strftime() เพื่อสร้างสตริงจากออบเจกต์ date มาแล้ว ตอนนี้เมื่อรู้จักออบเจกต์ datetime แล้ว ลองฝึกทำสิ่งที่คล้ายกัน
จำลองเมธอด .isoformat() ขึ้นมาใหม่โดยใช้ .strftime() แล้วพิมพ์เวลาเริ่มต้นของการเดินทางครั้งแรกในชุดข้อมูล
| Reference | |
|---|---|
| %Y | 4 digit year (0000-9999) |
| %m | 2 digit month (1-12) |
| %d | 2 digit day (1-31) |
| %H | 2 digit hour (0-23) |
| %M | 2 digit minute (0-59) |
| %S | 2 digit second (0-59) |
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การทำงานกับวันที่และเวลาใน Python
คำแนะนำการฝึกหัด
- กำหนด
fmtให้ตรงกับรูปแบบของ ISO 8601 - พิมพ์
first_startโดยใช้ทั้ง.isoformat()และ.strftime()ผลลัพธ์ที่ได้ควรตรงกัน
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Import datetime
from datetime import datetime
# Pull out the start of the first trip
first_start = onebike_datetimes[0]['start']
# Format to feed to strftime()
fmt = "____"
# Print out date with .isoformat(), then with .strftime() to compare
print(first_start.isoformat())
print(____)