Python Forum

Full Version: Trying to get the week number from a string of numbers
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I am parsing a json file and the string it returns the date as looks like this:
'2018-03-31T00:19:38Z'

This is ISO 8601 format. I have looked at various libraries to try to parse this and have gotten nothing to work.

I wrote some code that turns that into 2018-03-31. However that is still a string and for the functions I want to use in datetime I need to pass it a number.

This is what my code looks like now

from collections import Counter
import json
import datetime
import dateutil.parser


#List & json file stuffs
mylist = []
with open ('dates.txt') as a:
    data = json.load(a)

#Loop, count & clean
for dat in range(len(data)):
    test = (data[dat].get('commit').get('author').get('date'))
    test2 = test[:-10]
    #test3 = test2.replace("-", ", ")

    #datetime.date(2010, 6, 16).isocalendar()[1]
   # yourdate = dateutil.parser.parse(test, ignoretz=True)
   # new = datetime.date(yourdate)
     mylist.append(test)

#Show me the money
print (mylist)
There is other code commented out from other things I have tried.
Lookup casting a variable from one type to another https://www.peterbe.com/plog/interesting...-in-python
Try something like the following code. See https://docs.python.org/3/library/datetime.html

import dateutil.parser

s = '2018-03-31T00:19:38Z'
t = dateutil.parser.parse(s)
print("Default: {}".format(t))
print("Year: {}".format(t.year))
print("Month: {}".format(t.month))
print("Day of Month: {}".format(t.day))
weeknumber = int(t.strftime("%W"))
iweekday = int(t.strftime("%w"))
sdayofweek = t.strftime("%A")
sdayofweekshort = t.strftime("%a")
print("Week Number: {}".format(weeknumber))
print("Day of Week: {}".format(iweekday))
print("Day of Week: {}".format(sdayofweek))
print("Day of Week: {}".format(sdayofweekshort))
Output:
Default: 2018-03-31 00:19:38+00:00 Year: 2018 Month: 3 Day of Month: 31 Week Number: 13 Day of Week: 6 Day of Week: Saturday Day of Week: Sat
Lewis