change datetime object to string - python

I want to convert datetime.datetime(2016, 11, 21, 5, 34, 38, 826339, tzinfo=<UTC>) as Nov. 21, 2016, 11:04 a.m.
The time in the datetime object is in UST but I want it to be converted into IST(UST+ 05:30).
I tried using strftime as:
>>> datetime(2016, 11, 21, 5, 34, 38, 826339, tzinfo=<UTC>).isoformat(' ')
File "<stdin>", line 1
datetime(2016, 11, 21, 5, 34, 38, 826339, tzinfo=<UTC>).isoformat(' ')
^
SyntaxError: invalid syntax
Can I get some help here.
PS: I am using python
EDIT:
cr_date = datetime(2016, 11, 21, 5, 34, 38, 826339) #excluding the timezone
I can get partial desired reults by:
cr_date.strftime('%b. %d, %Y %H:%M')
'Oct. 31, 2013 18:23
didn't get the am/pm though

For the am/pm part, couldn't you use %p for the last field? I don't know python, I'm just assuming python is taking syntax from the unix date command.

Please find below code
from datetime import datetime
cr_date = datetime(2016, 11, 21, 5, 34, 38, 826339)
cr_date.strftime('%b. %d, %Y %H:%M %P')
'Nov. 21, 2016 05:34 am'

add %p for 'AM or PM' else add %P for 'am or pm'

Related

Convert UTC date string to PST and then subtract 12 hours from it

I have incoming strings that are UTC dates in ISO format like,
2021-11-21T12:16:42Z
I wish to convert these dates into PST and then subtract 12 hours from it.
import datetime
time_list_utc=2021-11-21T12:16:42Z
time_list_pst=time_list_utc.convert(pst)
print(time_list_pst-8hours)
I am new to datetime manipulation so any input is greatly appreciated
Use datetime, tzinfo and timedelta modules since Python 3.9:
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
s = '2021-11-21T12:16:42Z'
# Convert to datetime (UTC)
dt_utc = datetime.strptime(utc, "%Y-%m-%dT%H:%M:%S%z")
# Convert to PST
dt_pst = dt_utc.astimezone(ZoneInfo('US/Pacific'))
# Subtract 12 hours
dt = dt_pst - timedelta(hours=12)
Output:
>>> dt
datetime.datetime(2021, 11, 20, 16, 16, 42, tzinfo=zoneinfo.ZoneInfo(key='US/Pacific'))
>>> dt_pst
datetime.datetime(2021, 11, 21, 4, 16, 42, tzinfo=zoneinfo.ZoneInfo(key='US/Pacific'))
>>> dt_utc
datetime.datetime(2021, 11, 21, 12, 16, 42, tzinfo=datetime.timezone.utc)

Convert datetime from PDT to UTC in python

I have an object of <class 'datetime.datetime'>.
obj = datetime.datetime(2021, 6, 28, 2, 15, tzinfo=<FixedOffset '-07:00'>)
The time zone is PDT(offset -7:00). I need to convert it to UTC.
So if the object has datetime as 2021-05-02 10:00:00.000 -07:00.
It should be changed to 2021-05-02 17:00:00.000 +00:00.
How to achieve this in python?
Try the following, using .astimezone():
>>> import datetime
>>> obj = datetime.datetime.now()
>>> obj
datetime.datetime(2021, 7, 19, 13, 18, 26, 601212)
>>> obj.astimezone(tz=datetime.timezone.utc)
datetime.datetime(2021, 7, 19, 17, 18, 26, 601212, tzinfo=datetime.timezone.utc)
use time delta
bj = dt.datetime(2021,6,28,10,0)+dt.timedelta(hours=7)
pd.to_datetime(bj)

Why isn't my code working to make datetime objects timezone-aware?

I have two python datetime objects that represent the same moment in time:
a = datetime.datetime(2018, 10, 28, 13, 26, 30)
b = datetime.datetime(2018, 10, 28, 7, 26, 30)
Both are coming from different sources.
I know that the first is in UTC, and the second is in "America/Edmonton" (MDT).
Neither initially have a timezone attached to them.
I need to add timezones to these objects and compare them in a way where a == b is True.
What I did was this:
import datetime
from pytz import timezone
a = datetime.datetime(2018, 10, 28, 13, 26, 30)
b = datetime.datetime(2018, 10, 28, 7, 26, 30)
a = a.replace(tzinfo=timezone("UTC"))
b = b.replace(tzinfo=timezone("America/Edmonton"))
a = a.astimezone(timezone("America/Edmonton"))
b = b.astimezone(timezone("America/Edmonton"))
print(repr(a))
# Result: datetime.datetime(2018, 10, 28, 7, 26, 30, tzinfo=<DstTzInfo 'America/Edmonton' MDT-1 day, 18:00:00 DST>)
print(repr(b))
# Result: datetime.datetime(2018, 10, 28, 7, 26, 30, tzinfo=<DstTzInfo 'America/Edmonton' LMT-1 day, 16:26:00 STD>)
a == b # Results in False for some reason
What is "MDT-1 day, 18:00:00 DST" vs "LMT-1 day, 16:26:00 STD"? Why are they different? What am I doing wrong?
The proper way to do this appears to be:
import datetime
from pytz import timezone
a = datetime.datetime(2018, 10, 28, 13, 26, 30)
b = datetime.datetime(2018, 10, 28, 7, 26, 30)
a = timezone('UTC').localize(a)
b = timezone('America/Edmonton').localize(b)
a == b
As demonstrated here. This does result in a being equal to b. Still not sure why it sounds like pytz is defaulting to using a system from before 1893.

timezone conversion in Python

I'm probably missing something about timezones:
>>> import datetime, pytz
>>> date = datetime.datetime(2013,9,3,16,0, tzinfo=pytz.timezone("Europe/Paris"))
>>> date.astimezone(pytz.UTC)
datetime.datetime(2013, 9, 3, 15, 51, tzinfo=<UTC>)
I was expecting
datetime.datetime(2013, 9, 3, 15, 00, tzinfo=<UTC>)
Can anyone explain me where these 51 minutes come from?
Thanks,
Jean-Philippe
The UTC offset gives (date.tzinfo.utcoffset(date)):
datetime.timedelta(0, 540)
This is 540 seconds or 9 minutes.
In France the switch to UTC was made on March 11, 1911 and the clocks were turned back 9 minutes and 21 seconds (source 1, source 2):
Until 1911, Paris was 9 minutes and 21 seconds off UTC.
You can also see it here (Paris time in 1911) where the time goes from March 11, 12:01:00 AM to March 10, 11:51:39 PM.
Read the note at the very begining of pytz documentation ; use .localize() method to create timezone-aware datetime object:
import datetime
import pytz
naive_dt = datetime.datetime(2013,9,3,16,0)
dt = pytz.timezone("Europe/Paris").localize(naive_dt, is_dst=None)
to_s = lambda d: d.strftime('%Y-%m-%d %H:%M:%S %Z%z')
print(to_s(dt))
print(to_s(dt.astimezone(pytz.utc)))
Output
2013-09-03 16:00:00 CEST+0200
2013-09-03 14:00:00 UTC+0000
I don't know why you are expecting 15:00 UTC here.
Thanks Simeon for your answer. It made me realize how shallow is my understanding of all of this. The following experimentations lost me a little more...
>>> import datetime, pytz
>>> date_paris = datetime.datetime(2013,9,3,16,0, tzinfo=pytz.timezone("Europe/Paris"))
>>> date_utc = datetime.datetime(2013,9,3,16,0, tzinfo=pytz.utc)
>>> date_paris.astimezone(pytz.utc)
datetime.datetime(2013, 9, 3, 15, 51, tzinfo=<UTC>)
>>> date_utc.astimezone(pytz.timezone("Europe/Paris"))
datetime.datetime(2013, 9, 3, 18, 0, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>)
Why this 9 minutes offset shows up when converting in one direction but not the other? The following piece of code concentrate all disappointment:
>>> date_paris
datetime.datetime(2013, 9, 3, 16, 0, tzinfo=<DstTzInfo 'Europe/Paris' PMT+0:09:00 STD>)
>>> date_paris.astimezone(pytz.utc).astimezone(pytz.timezone("Europe/Paris"))
datetime.datetime(2013, 9, 3, 17, 51, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>)

Calculating a timewindow with Python datetime

I'd like to query my DB for all records posted on a particular day (e.g. today between 00:00 and 23:59:59) given a datetime.datetime timestamp such as datetime.datetime(2010, 12, 21, 17, 59, 43, 85335).
What's the best method to calculate the start and end datetime.datetime instances, please? I'd like to end up with something like this:
>>> timestamp = datetime.datetime(2010, 12, 21, 17, 59, 43, 85335)
>>> # do something with timestamp to get start_date and end_date
>>> start_date
datetime.datetime(2010, 12, 21, 0, 0, 0, 0)
>>> end_date
datetime.datetime(2010, 12, 21, 23, 59, 59, 0)
Thanks, HC
Ah, found what I want. I struggle with datetime every time.
>>> timestamp = datetime.datetime.now()
>>> timestamp
datetime.datetime(2010, 12, 21, 18, 31, 37, 900795)
>>> timestamp.replace(hour=0, minute=0, second=0, microsecond=0)
datetime.datetime(2010, 12, 21, 0, 0)
If it's just calculating a day, then what you have is fine. Just use the day and then put the hour as 0:00 and 23:59 respectively.
If you want to get the start and end times of a month, that gets a lot more complicated since months have different days. For something like that you could use this module
http://niemeyer.net/python-dateutil
timedelta sounds just like what you need.
http://docs.python.org/library/datetime.html#timedelta-objects
from datetime import datetime, date
date.today() - timedelta(days=7)
Will give you 7 days from today.

Categories