Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to get UTC time
#1
Hi,
I use below code

from datetime import datetime
print(datetime.utcnow())
my output as below:
2021-12-26 00:25:14.083291

but I want like this: 2021-12-26T00:25:14.083291+0800
can any one suggest how to achieve this.
Reply
#2
I would suggest using Pendulum.
Then default is UTC and deal much better with time zones than datetime,
which need a combination with tzinfo, pytz when dealing with time zones.
>>> import pendulum
>>> 
>>> now = pendulum.now()
>>> now
DateTime(2021, 12, 26, 1, 33, 9, 533323, tzinfo=Timezone('Europe/Berlin'))
>>> print(now)
2021-12-26T01:33:09.533323+01:00
BashBedlam likes this post
Reply
#3
(Dec-26-2021, 12:56 AM)snippsat Wrote: I would suggest using Pendulum.
Then default is UTC and deal much better with time zones than datetime,
which need a combination with tzinfo, pytz when dealing with time zones.
>>> import pendulum
>>> 
>>> now = pendulum.now()
>>> now
DateTime(2021, 12, 26, 1, 33, 9, 533323, tzinfo=Timezone('Europe/Berlin'))
>>> print(now)
2021-12-26T01:33:09.533323+01:00




NameError: name 'DateTime' is not defined

ImportError: cannot import name 'DateTime' from 'datetime' (C:\Users\mekal\Anaconda3\lib\datetime.py)

from datetime import DateTime
import pendulum

now = pendulum.now()
now
DateTime(2021, 12, 26, 1, 33, 9, 533323, tzinfo=Timezone('Europe/Berlin'))
print(now)
Reply
#4
Why are you trying to import DateTime from the standard library datetime module, when it's clearly a type from pendulum as snippsat's code shows?
Reply
#5
As mention there is no need to import datetime,and in my code i do not do that.
Doc Wrote:Pendulum is a Python package to ease datetimes manipulation.

It provides classes that are drop-in replacements for the native ones (they inherit from them).

Special care has been taken to ensure timezones are handled correctly, and are based on the underlying tzinfo implementation.
For example, all comparisons are done in UTC or in the timezone of the datetime being used.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020