I have a Django project where I used the strftime function like this in models.py:
class Email(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="emails") sender = models.ForeignKey("User", on_delete=models.PROTECT, related_name="emails_sent") recipients = models.ManyToManyField("User", related_name="emails_received") subject = models.CharField(max_length=255) body = models.TextField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) archived = models.BooleanField(default=False) def serialize(self): return { "id": self.id, "sender": self.sender.email, "recipients": [user.email for user in self.recipients.all()], "subject": self.subject, "body": self.body, "timestamp": self.timestamp.strftime("%b %-d %Y, %-I:%M %p"), "read": self.read, "archived": self.archived }
However, for some reason this returns a ValueError, even though according to a documentation (https://www.programiz.com/python-programming/datetime/strftime) this is a valid format string. Once I removed all the dashes, it worked normally. Why doesn’t this work? Do I need to import a module or something? Thanks.
Advertisement
Answer
To @jsonharper’s comment, here’s a link to the official Python 3 docs: https://docs.python.org/3.0/library/datetime.html#strftime-behavior As he pointed out, that site notes platform variations are common and does not list “-” as a commonly-accepted format specifier.