0

I wrote the following function to convert UTC to CST (which is working fine):

import datetime

def utc_datetime_to_cst_1(dt_now):
    """
    To convert UTC into CST, subtract 6 hours
    During daylight saving (summer) time, you would only subtract 5 hours

    :param dt_now: current date time - UTC format
    :return: CST datetime
    """
    # UTC is 6 hours ahead CST
    dt_now = dt_now - datetime.timedelta(hours=6)

    # If DST, increment one hour
    # IGNORE THIS PART FOR NOW
    #dt_now = dt_now + datetime.timedelta(hours=1)

    # Return CST datetime
    return dt_now

I was trying to create a better way so I came with this function:

import datetime
from pytz import utc, timezone

def utc_datetime_to_cst_2(date_time):
    """
    Converts UTC date time to CST

    :param date_time: date time
    :return: date time in CST
    """
    # Load current date as UTC
    utc_now = utc.localize(date_time)
    eastern = timezone('US/Eastern')

    # Return as CST
    return utc_now.astimezone(eastern)

When calling both:

current_datetime = datetime.datetime(year=2019, month=12, day=2, hour=23)
print(current_datetime)
print(utc_datetime_to_cst_1(current_datetime))
print(utc_datetime_to_cst_2(current_datetime))

I get the following:

2019-12-02 23:00:00
2019-12-02 17:00:00
2019-12-02 18:00:00-05:00

So utc_datetime_to_cst_2 is not converting the way I expect since I should have now()-6h. Any ideas?

Thank you!

briba
  • 2,857
  • 2
  • 31
  • 59

0 Answers0