Ad
Loop Through A List Of Date Strings: Strptime Outputs "Datetime.date(2011-7-5)" Instead Of (2011-7-5)
I have the following problem:
I have a list of date strings:
dates = ['11-07-05',
'11-07-01',
'11-07-03',
'11-07-04', etc]
I want to convert them into date formats and i have used the following code:
from datetime import datetime as dt
dateFormat = [dt.strptime(item[1],"%y-%m-%d").date() for item in dates
this should output a new list in the following format:
dateFormat = [2011-7-5,
2011-7-1,
2011-7-3,
2011-7-4]
but the output turns out to be:
dateFormat = [datetime.date(2011-7-5),
datetime.date(2011-7-1),
datetime.date(2011-7-3),
datetime.date(2011-7-4)]
My question is: How can i format the date strings into date format without the "datetime.date"?
Ad
Answer
You want to convert the string to datetime using datetime.strptime and then convert the datetime back to string using datetime.strftime
from datetime import datetime as dt
dates = ['11-07-05', '11-07-01', '11-07-03', '11-07-04']
# Iterate through the dates
# Convert string to datetime using strptime
# and then convert the datetime back to string using strftime
dateFormat = [dt.strptime(item,"%y-%m-%d").date().strftime('%Y-%m-%d') for item in dates]
print(dateFormat)
The output will be
['2011-07-05', '2011-07-01', '2011-07-03', '2011-07-04']
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad