how to convert pywintypes.datetime to different format

1.3k Views Asked by At

I have an object x which is as below

x = '2020-06-15 00:00:00+00:00'

print(x)
2020-06-15 00:00:00+00:00
print(type(x))
<class 'pywintypes.datetime'>

I want to convert above object to 2020-06-15 format and also to Year-Quarter format i.e. 2020 Q2

Is there any way to achieve this?

3

There are 3 best solutions below

2
Nebula Darwin On

Maybe this can help you....

from math import ceil
x = '2020-06-15 00:00:00+00:00'
date, time = x.split()
yy, mm, dd = date.split('-')

print(f'{yy} - Q{ceil(int(mm)/3)}')
0
FObersteiner On

you have methods available as you have for the datetime.datetime class, so you can use .year and .month attributes. Ex:

import math
# --- Windows-specific! ---
import pywintypes
import win32timezone

t = pywintypes.Time(1592179200).astimezone(win32timezone.TimeZoneInfo('UTC'))

print(t)
# 2020-06-15 00:00:00+00:00

print(f'{t.year}-Q{math.ceil(int(t.month)/3)}')
# 2020-Q2
0
Umar Shahid On

UPDATED 30-1-2023

The code below will help to convert your given time to your required time

import datetime as dt

_datetime_str = '2020-06-15 00:00:00+00:00'
_splitted_datetime_str = x.split("+")
# output: ['2020-06-15 00:00:00', '00:00']

_datetime = dt.strptime(_splitted_datetime_str[0], "%Y-%m-%d %H:%M:%S")
# output datetime.datetime(2020, 06,15, 00, 00, 00)