Home > Software design >  Date to datetime with timezone
Date to datetime with timezone

Time:02-19

How would I convert

"2022-02-01" to something like

"2022-02-01T()" there are no brackets I'd like to convert each 30 minute interval from 2022-02-01 00:30:00 H:M:S and so forth.

I wanted to use something like

startDates = [{'start': {'date': '2022-02-01'}}]  # Minimal Reproducible Example
timeZone = pytz.timezone('America/Vancouver')
for event in startDates:
    newStartDateTime = datetime.strptime(event['start']['date'], '%Y-%m-%d' )
    print(newStartDateTime)
    datetime_ist = datetime.strptime(event['start']['date'], '%Y-%m-%d' ).replace(tzinfo=timeZone)
    print("Date & Time in : ",datetime_ist.strftime('%Y-%m-%dT%H:%M:%S%z'))

Which does produce a time slot at the first H:M:S I'd to obtain 48 of these

2022-02-01 00:00:00
Date & Time in :  2022-02-01T00:00:00-0812

CodePudding user response:

First, make your datetime object timezone aware, using py.timezone.localize(datetime). And then convert it using astimezone().

For the 30-minute increments, use datetime.timedelta to keep adding 30 mins to your newStartDateTime.

from datetime import datetime, timedelta
import pytz

vancouver_tz = pytz.timezone('America/Vancouver')
ist_tz = pytz.timezone('Asia/Calcutta')

startDates = [{'start': {'date': '2022-02-01'}}]  # Minimal Reproducible Example
for event in startDates:
    newStartDateTime = datetime.strptime(event['start']['date'], '%Y-%m-%d')
    vancouver_time = vancouver_tz.localize(newStartDateTime)
    india_time = vancouver_time.astimezone(tz=ist_tz)
    print("first Date & Time in IST:", india_time.strftime('%Y-%m-%dT%H:%M:%S%z'))
    
    # now add increasing timedeltas in minute chunks
    for delta in range(0, 30 * 48, 30):
        offsetted_ist = india_time   timedelta(minutes=delta)
        print("Date & Time in IST:", offsetted_ist.strftime('%Y-%m-%dT%H:%M:%S%z'))

Output:

first Date & Time in IST: 2022-02-01T13:30:00 0530
Date & Time in IST: 2022-02-01T13:30:00 0530
Date & Time in IST: 2022-02-01T14:00:00 0530
Date & Time in IST: 2022-02-01T14:30:00 0530
...
Date & Time in IST: 2022-02-02T12:00:00 0530
Date & Time in IST: 2022-02-02T12:30:00 0530
Date & Time in IST: 2022-02-02T13:00:00 0530

Btw, choose if you want to use camelCase or lowercase_with_underscores for your variables. Pick one. Python is typically lowercase_with_underscores, except classes which are UpperCamelCase.

  • Related