1

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?

Bogaso
  • 2,838
  • 3
  • 24
  • 54
  • review this links https://stackoverflow.com/questions/39028290/python-convert-pywintyptes-datetime-to-datetime-datetime – andresfv95 Jan 10 '22 at 01:42

3 Answers3

2

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)}')
  • +1 as I borrowed your last line ;-) I think it is better though to work with the class methods instead of converting to string and then splitting the string etc. – FObersteiner Jan 10 '22 at 08:04
  • Yeah, actually the asker already assumed to be having a string of datetime at some point of time, so I delivered a fool-proof solution right from that position – Nebula Darwin Jan 11 '22 at 03:58
2

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
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
0

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)