如何将datetime对象转换为日期?

时间:2016-04-26 16:48:01

标签: python django datetime

我在尝试从datetime对象中获取日期时收到以下错误:

dateMondayRef.update(obj1)
dateTuesdayRef.update(obj2)
// or
dateMondayRef.child(dateMonday).set({emp1: ...})
dateTuesdayRef.child(dateTuesday).set({emp1: ...})

时间戳的格式为

must be string, not datetime.datetime

这是models.py:

Tue, 26 Apr 2016 22:12:00 +0530

这是对象类:

class Order(models.Model):
    ORDER_STATUS = (
        ('created' , 'Created') , 
        ('paid','Paid'),
        ('shipped','Shipped'),
        ('refunded','Refunded'),
        )

    status = models.CharField(max_length=120 , choices=ORDER_STATUS , default='created')
    cart = models.ForeignKey(Cart)
    user = models.ForeignKey(UserCheckout , null=True)
    address = models.ForeignKey(UserAddress , related_name='useraddress' , null=True)
    Order_total_price = models.DecimalField(max_digits=10 , decimal_places=2)
    order_id = models.CharField(max_length=20 , null=True , blank=True )
    timestamp = models.DateTimeField(auto_now_add=True , auto_now=False)

    def __unicode__(self):
        return str(self.user)

class SubOrder(models.Model):
    order = models.ForeignKey('orders.Order')
    store = models.ForeignKey(Store)
    store_order_id=models.CharField(max_length=300)
    items = models.ManyToManyField(StoreProduct,through=StoreOrderItem)
    read = models.BooleanField(default=False)
    store_order_amount = models.DecimalField(max_digits=50 , decimal_places=2)

这是追溯:

import datetime


class ChartData(object): 
    @classmethod  
    def check_order_data(self):
        data = {'order_numbers': [], 'order_price': [] , 'date' : []}

        orders = SubOrder.objects.all()

        for order in orders:
            print str(order.order.timestamp)
            print datetime.datetime.strptime(order.order.timestamp, "%Y-%m-%d %H:%M:%S.%f")
            data['order_numbers'].append(str(order.id))
            data['date'].append(order.order.timestamp)
            data['order_price'].append(int(order.store_order_amount))
            print data
        return data  

如何解决上述错误?提前谢谢。

3 个答案:

答案 0 :(得分:1)

功能datetime.datetime.strptime必须收到date_stringstring_format

如果要从datetime.datetime对象获取字符串,则应使用strftime函数。

答案 1 :(得分:0)

datetime.datetime.strptime()string转换为datetime个对象。

datetime.datetime.strftime()是将datetime对象转换为指定的string

datetimestring

>>> datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
'2016-04-26 22:22:39.720617'

stringdatetime

>>> datetime.datetime.strptime('2016-04-26 22:22:39.720617', '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2016, 4, 26, 22, 22, 39, 720617)

答案 2 :(得分:0)

为了从datetime对象中获取日期,我使用了这个:

datetime.datetime.strftime(order.order.timestamp, "%Y-%m-%d")