我想分割日期並將其轉換爲整數。如果我按照以下方式放置代碼,我還可以嗎? birthdate = '10/08/78'
bmonth, bday, byear = birthdate.split('/')
列表中,將字符串轉換爲整數
回答
理想的方式實現這一目標是通過使用模塊:
>>> from datetime import datetime
>>> date = datetime.strptime('10/08/78', '%m/%d/%y')
>>> date.month, date.day, date.year
(10, 8, 1978)
# ^Returns complete year
但如果你只是想從格式中提到的字符串中提取它。你可以按照你提到的方式去做。
>>> month, day, year = '10/08/78'.split('/')
>>> month, day, year
('10', '08', '78')
# ^you get as it is value
順便說一句:如果'locale'爲'en_US',你可以使用'%x'作爲'strptime'格式 – AChampion
您的代碼不會創建整數。您的bmonth, bday, byear
變量將保存字符串值。
得到你需要使用下面的代碼的整數:
birthdate = '10/08/78'
birthdate_split = list()
for item in birthdate.split('/'):
birthdate_split.append(int(item))
bmonth, bday, byear = birthdate_split
你知道比'bmonth = int(bmonth)短的方法嗎?bday = int(bday) byear = int(byear)' –
'bmonth,bday,byear = map(int,birthdate.split('/'))''參見@MoinuddinQuadri使用'datetime'回答 - 這是最好的方法。 – AChampion
我想使用日期時間,但我必須這樣 –
from datetime import datetime
date=datetime.strptime('10/08/1978', '%m/%d/%Y')
date.month
- 1. 轉換整數列表爲字符串
- 2. 將字符串的混合列表轉換爲整數列表
- 3. 將整數列表轉換爲字符串列表
- 4. 如何將字符串列表轉換爲整數列表?
- 5. 將字符串列表轉換爲整數列表
- 6. 如何將字符串轉換爲整數列表的列表?
- 7. 將字符串轉換爲Erlang中的整數列表
- 8. 如何將字符串列表轉換爲Python中的整數?
- 9. 將字符串轉換爲字列表?
- 10. 將字符串轉換爲整數
- 11. Swift:將字符串轉換爲整數
- 12. 將字符串轉換爲整數
- 13. 將字符串轉換爲整數
- 14. 將字符串轉換爲整數
- 15. 將字符串轉換爲整數?
- 16. 將字符串轉換爲整數
- 17. 將整數轉換爲字符串
- 18. 將字符串轉換爲整數
- 19. 將整數值轉換爲字符串
- 20. 將整數轉換爲字符串-mysql
- 21. 將JavaScript字符串轉換爲整數
- 22. 將字符串值轉換爲整數
- 23. 將字符串轉換爲整數?
- 24. 將整數轉換爲字符串
- 25. 將字符串轉換爲整數
- 26. 將字符串轉換爲整數Android
- 27. 將字符串轉換爲整數
- 28. 將整數轉換爲字符串
- 29. 將字符串轉換爲整數
- 30. 將字符串轉換爲整數
嗯........是嗎? – TigerhawkT3
如果你用'birthdate'替換'birthday',那麼是(反之亦然) - 只保留變量名稱一致。 – grammar31
我的錯誤,它假設是'bmonth,bday,byear = birthdate.split('/')' –