In python, how do I create a timezone aware datetime from a date and time?

后端 未结 2 520
悲&欢浪女
悲&欢浪女 2021-02-07 14:02

In Python, let\'s say I have a date of 25 December 2016. How can I create a timezone-aware datetime of noon on that date?

Bonus points if it\'s compatible with Django\'

2条回答
  •  情深已故
    2021-02-07 14:59

    The trick is to first combine the naive time and the date into a naive datetime. This naive datetime can then be converted to an aware datetime.

    The conversion can be done using the third party package pytz (using, in this case, the 'Europe/London' timezone):

    import datetime
    import pytz
    
    naive_time = datetime.time(0, 30)
    date = datetime.date(2016, 12, 25)
    naive_datetime = datetime.datetime.combine(date, naive_time)
    
    timezone = pytz.timezone('Europe/London')
    aware_datetime = timezone.localize(naive_datetime) 
    

    If you're doing it in Django, and want to use the current timezone (as configured in Django), you can replace the final two lines with a call to make_aware:

    from django.utils import timezone
    
    aware_datetime = timezone.make_aware(naive_datetime)
    

提交回复
热议问题