0

I'm using boto3 and python to get information about objects in an S3 bucket. I' using boto as below:

context = super(s3, self).get_context_data(**kwargs)
    data = []
    aws = boto3.resource('s3')
    buckets = aws.buckets.all()
    #Get data from each bucket
    for bucket in buckets:
        bucketData = {}
        totalSize = 0
        bucketName = bucket.name
        fileBuckets = boto3.resource('s3').Bucket(bucketName)
        #Get data for each object inside each bucket
        for file in fileBuckets.objects.all():
            totalSize += file.size
        bucketData['bucketName'] = bucket.name
        bucketData['createdAt'] = bucket.creation_date
        bucketData['totalSize'] = file_size(totalSize)
        data.append(bucketData)
    context['buckets'] = data
    return context

And I display the creation date in the template like this:

<ul id='s3ItemDesc'>
        <li>{{ bucket.createdAt }}</li>
          <li>{{ bucket.totalSize }}/4GB</li>
        <li>

This is fine however I want to change the datetime stamp to just date. Currently I'm getting this:

Dec. 3, 2017, 2:11 p.m

But I would like to change it to display date only:

3/12/2017

I've been googling for a while but couldn't find anything. Any idea how this can be achieved?

davidb
  • 1,503
  • 4
  • 30
  • 49
  • Which template engine are you using? According to [docs](http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Bucket.creation_date) `bucket.creation_date` is a `datetime` object. So I think, the display style resp. string format is set by the template engine – albert Dec 14 '17 at 21:42
  • I'm using Jinja – davidb Dec 14 '17 at 21:44
  • Try `{{ bucket.creation_date.strftime('%-d/%m/%Y') }}` – albert Dec 14 '17 at 21:46
  • I get an invalid format string error. – davidb Dec 14 '17 at 21:57
  • Which OS are you working on? Does `.strftime('%d/%m/%Y')` or `.strftime('%m/%Y')` work? – albert Dec 14 '17 at 22:11
  • I tested this `time = datetime.now` and then `d = datetime.strptime(str(time), '%Y-%m-%d %H:%M:%S')` but this didn't work neither. – davidb Dec 14 '17 at 22:31
  • Possible duplicate of [Python: How do I format a date in Jinja2?](https://stackoverflow.com/questions/4830535/python-how-do-i-format-a-date-in-jinja2) – albert Dec 14 '17 at 22:39
  • I think I was wrong. I'm just using plain django, no templating engine(at least I think so). I don't really understand the code in that thread. – davidb Dec 14 '17 at 22:42

1 Answers1

0

Assuming you're using Django's template engine you can apply a filter to modify the date format as follows:

{{ bucket.creation_date|date:"d m Y" }}

For more information please refer to the docs about date templating and date formatting.

albert
  • 8,027
  • 10
  • 48
  • 84