Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert pendulum to datetime.datetime type?

In current part of system pendulum v1.4 is used, but with croniter it causing error described in https://github.com/sdispater/pendulum/issues/214

This works fine with datetime.datetime type and i still have to stay with pendulum v1.4.

So i am looking for solution how to efficiently to convert pendulum to datetime.datetime type ?

Already tried formatting pendulum as string and parsing using dateutil.parser.

like image 514
esugei Avatar asked Jan 03 '19 19:01

esugei


4 Answers

Another take on this:

>>> from datetime import datetime
>>> import pendulum
>>> datetime.fromtimestamp(pendulum.now().timestamp(), pendulum.tz.UTC)
datetime.datetime(2021, 1, 12, 11, 41, 32, 387753, tzinfo=Timezone('UTC'))

Usually there should be no need to do this since pendulum's DateTime inherits from datetime.datetime. Any code working with stdlib's datetime's should work with pendulum's as well.

like image 106
tosh Avatar answered Nov 07 '22 01:11

tosh


pendulum==1.4.0 objects have the protected _datetime member:

import pendulum

p = pendulum.now()
p._datetime

This will give you something like

datetime.datetime(2021, 5, 24, 12, 44, 11, 812937, tzinfo=<TimezoneInfo [America/New_York, EDT, -4:00:00, DST]>)

Another way is as follows: and works for pendulum==1.4.0 and more recent pendulum==2.1.2

import pendulum
from datetime import datetime

p = pendulum.now()
datetime_string = p.to_datetime_string()
datetime.fromisoformat(datetime_string)

which will give

datetime.datetime(2021, 5, 24, 12, 44, 11)
like image 37
Ali Cirik Avatar answered Nov 07 '22 02:11

Ali Cirik


I couldn't find a Pendulum helper for this either. So, back to basics:

import datetime as dt

tz_info = dateutil.tz.gettz(zone_name)
pend_time = pendulum.datetime(...)

dt_time = dt.datetime(
    pend_time.year,
    pend_time.month,
    pend_time.day,
    pend_time.hour,
    pend_time.minute,
    pend_time.second,
    pend_time.microsecond,
).astimezone(tz_info)

Note the use of dateutil. As of Python 3.6, the tzinfo documentation recommends dateutil.tz rather than pytz as an IANA time zone provider.

like image 4
Gavin Avatar answered Nov 07 '22 01:11

Gavin


The following code works for me:

In [1]: import pendulum

In [2]: import datetime

In [3]: pdt = pendulum.now()

In [4]: datetime.datetime.fromisoformat(pdt.to_iso8601_string())
Out[4]: datetime.datetime(2022, 2, 22, 14, 29, 36, 812772,tzinfo=datetime.timezone(datetime.timedelta(seconds=28800)))
like image 1
dindom Avatar answered Nov 07 '22 01:11

dindom