簡體   English   中英

Python datetime isoformat - 從字符串計算直到 bithday 的天數 - 轉換為 datetime.datetime object

[英]Python datetime isoformat - count days until bithday from string - convert into datetime.datetime object

我想計算直到生日的天數。 我有出生日期的字符串:

"1949-10-09T00:25:51.304Z"

tday = datetime.now().isoformat()

返回

2020-08-05T21:02:31.532123
<class 'str'>

我想知道如何創建這兩個字符串的增量時間。

我看到了這些字符串之間的區別:

"1949-10-09T00:25:51.304Z"     # date of birth
"2020-08-05T21:02:31.532123"   # today

我是否必須更改“今天”字符串(切片以獲取:

"2020-08-05T21:02:31.532"

然后連接“Z”得到:

"2020-08-05T21:02:31.532Z"

然后使用 datetime.strptime() 將其轉換為 object,並將生日日期也轉換為 object 日期,使用這個?

birthday = datetime.fromisoformat('1949-10-09T00:25:51.304Z')

還是有更聰明的方法來做到這一點?

要獲得生日字符串,我必須使用解析 JSON 文件的 function 。

date=get_double_nested_table_data(0, "dob", "date")
birthday = datetime.fromisoformat(date)
now = datetime.now()
delta = now - birthday

它不起作用。

我使用下面的答案做到了這一點:

def get_days_until_birthday(index: int, first_table: str, second_table: str):
    birthday_str = get_double_nested_table_data(index, first_table, second_table)
    birthday = datetime.strptime(birthday_str, "%Y-%m-%dT%H:%M:%S.%fZ")
    now = datetime.now()
    delta = now - birthday
    return delta.days

並返回這樣的行:奇怪的整數

我將 function 更改為:

def get_days_until_birthday(index: int, first_table: str, second_table: str):
    now = datetime.now()
    year = now.year
    birthday_str = get_double_nested_table_data(index, first_table, second_table)
    birthday_str = str(year) + birthday_str[4:]
    birthday = datetime.strptime(birthday_str, "%Y-%m-%dT%H:%M:%S.%fZ")
    now = datetime.now()
    delta = now - birthday
    return delta.days

並且只有在今年生日到來的情況下才能正常工作。 如果生日將在明年,則 function 不會返回正確的日期。

你能知道如何改變嗎?

你想要的是減去兩個日期時間,這給你它們之間的時間增量

from datetime import datetime

birthday_str = '1949-10-09T00:25:51.304Z'
# you can remove the Z by slicing
birthday = datetime.fromisoformat(birthday_str[:-1])
# or with strptime
birthday = datetime.strptime(birthday_str, "%Y-%m-%dT%H:%M:%S.%fZ")
now = datetime.now()
delta = now - birthday

# return the number of days (positive) there is between now and birthday date
return (now - birthday).days if birthday < now else (birthday - now).days

strptime 格式參考

%Y是 4 年的年份*
%m * 2 位數的月份
2 位數的%d
T仍然匹配您正在使用的字符串的格式
%H是小時
仍然匹配您正在使用的字符串的格式
%M是分鍾
%S是秒
. 仍然匹配您正在使用的字符串的格式
%f是微秒
Z仍然匹配您正在使用的字符串的格式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM