一、Y-M-D格式轉換為時間戳
Python中的datetime模塊提供了一個時間對象,可以方便地進行時間和日期值的操作。特別是,datetime對象可以與時間戳相互轉換。在Python中,可以使用time模塊的time()函數來獲取當前的時間戳。如果要將Y-M-D格式的日期轉換成時間戳,可以使用datetime.strptime()方法來將日期字元串轉換成datetime對象,然後使用datetime.timestamp()方法將其轉換為時間戳。
import datetime import time date_string = "2022-10-01" date_object = datetime.datetime.strptime(date_string, "%Y-%m-%d") timestamp = date_object.timestamp() print(timestamp)
二、時間戳轉換為Y-M-D格式
有時候我們需要將時間戳轉換為Y-M-D格式的日期字元串。可以使用datetime模塊的fromtimestamp()方法將時間戳轉換成datetime對象,然後使用strftime()方法將datetime對象格式化為Y-M-D格式的日期字元串。
import datetime import time timestamp = 1664552400 date_object = datetime.datetime.fromtimestamp(timestamp) date_string = date_object.strftime("%Y-%m-%d") print(date_string)
三、Y-M-D格式轉換為其他格式
有時候我們需要將Y-M-D格式的日期字元串轉換為其他格式的日期字元串。可以使用datetime模塊的strptime()方法將日期字元串轉換成datetime對象,然後使用strftime()方法將其轉換為需要的格式。
import datetime date_string = "2022-10-01" date_object = datetime.datetime.strptime(date_string, "%Y-%m-%d") new_date_string = date_object.strftime("%B %d, %Y") print(new_date_string)
在上述示例中,將Y-M-D格式的日期字元串轉換為”B d, Y”格式的字元串,其中”%B”表示月份的完整名稱,”%d”表示日期,”%Y”表示年份。
四、練習題
請嘗試編寫一個Python程序,實現以下功能:
- 將當前日期字元串轉換為時間戳並輸出
- 將當前時間戳轉換為Y-M-D格式並輸出
- 將當前日期字元串轉換為”Month day, year”格式(例如:October 01, 2022)並輸出
import datetime import time # 將當前日期字元串轉換為時間戳並輸出 current_time = time.time() print(current_time) # 將當前時間戳轉換為Y-M-D格式並輸出 current_date = datetime.datetime.fromtimestamp(current_time) current_date_str = current_date.strftime("%Y-%m-%d") print(current_date_str) # 將當前日期字元串轉換為"Month day, year"格式並輸出 current_date_str = datetime.datetime.now().strftime("%B %d, %Y") print(current_date_str)
在上述示例中,首先使用time模塊的time()函數獲取當前時間戳,然後使用datetime模塊的fromtimestamp()方法將其轉換成datetime對象並輸出。接著,使用datetime模塊的strftime()方法將當前日期字元串按要求格式化並輸出。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/304218.html