python datetime now timezone code example

Example 1: python time now other timezone

#as an aware datetime
from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time


#or from pytz database
import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

Example 2: datetime python

from datetime import datetime as d
date = d.now()
print(date.strftime("%Y-%m-%d %H:%M:%S"))

Example 3: python date and time

from datetime import datetime
now = datetime.now()
print (now.strftime("%Y-%m-%d %H:%M:%S"))


Output: 2020-06-19 10:34:45

Example 4: datetime python timezone

import datetime
import pytz
my_date = datetime.datetime.now(pytz.timezone('US/Pacific'))

Example 5: python datetime now

import datetime
print(datetime.datetime.now()) #datetime.datetime.now() is the syntax

Example 6: python set timezone of datetime

datetime_with_timezone = datetime.datetime(2019, 2, 3, 6, 30, 15, 0, pytz.UTC)