converting timestamp to datetime in python - python-3.x

I have a timestamp which is coming from a remote Linux box. This is the timestamp 1356354496.
When I am using the fromtimestamp function I am getting a different output then what it should be.
Example:
from datetime import datetime
import time
print(time.ctime(int("1356354496")))
cwStartTimeDisplay=datetime.fromtimestamp(int("1356354496")).strftime("%a %b %d %H:%M:%S %Y")
print(cwStartTimeDisplay)
Output
Mon Dec 24 05:08:16 2012
Mon Dec 24 05:08:16 2012
Whereas I should be getting 12/24/2012 6:38:16 PM. I am a beginner and don't really know if tz parameter is the answer to this. Can anybody help please?

Your timestamp seems to be UTC, so if you need id represented in IST, you need to convert it.
The recommended library to work with timezone data in python is pytz
from datetime import datetime
import pytz
ist = pytz.timezone("Asia/Kolkata")
utcdate = pytz.utc.localize(datetime.utcfromtimestamp(1356354496))
print("UTC:", utcdate)
istdate = ist.normalize(utcdate)
print("IST:", istdate)
# or shorter:
date = datetime.fromtimestamp(1356354496, ist)
print("IST:", date)
output:
UTC: 2012-12-24 13:08:16+00:00
IST: 2012-12-24 18:38:16+05:30
IST: 2012-12-24 18:38:16+05:30

Related

converting string date time with microseconds to date object

I have a datetime coming from json data as 2017-03-28T00:00:00.000Z
I have tried this
datetime.datetime.strptime(record_date, "%Y-%m-%d%H:%M:%S%f")
but this gives error:
*** ValueError: time data '2017-03-28T00:00:00.000Z' does not match format '%Y-%m-%d%H:%M:%S%f'
I have to compare the read date with user input date as 2017-03-28 format
Your time is in isoformat, you need to use datetime's fromisoformat to convert it into a datetime object.
The [:-1] is to exclude the Z because datetime does not understand what that is. (2017-03-28T00:00:00.000Z is actually RFC 3339)
Z basically means UTC timezone (+00:00 GMT)
from datetime import datetime
foo = "2017-03-28T00:00:00.000Z"
bar = datetime.fromisoformat(foo[:-1])
print(bar)
print(type(bar))
Gives you the result of, but this is now naive (unaware of timezone)
2017-03-28 00:00:00
<class 'datetime.datetime'>
A quick workaround to make it timezone aware is
bar = datetime.fromisoformat(foo.replace('Z', '+00:00'))
print(bar)
2017-03-28 00:00:00+00:00
#If milliseconds are of concern then just strftime
bar = datetime.fromisoformat(foo.replace('Z', '+00:00')).strftime("%Y-%m-%d %H:%M:%S:%f %Z")
# the Z displays UTC or equivalent time zone
2017-03-28 00:00:00:000000 UTC
The dateutil module is even better at handling this as it has native support for RFC 3339.
import dateutil.parser
foo = "2017-03-28T00:00:00.000Z"
bar = dateutil.parser.isoparse(foo)
print(bar)
print(type(bar))
2017-03-28 00:00:00+00:00
<class 'datetime.datetime'>

Convert date and time from UTC to local in specifed format

I have UTC date time as 2021-02-24 12:41:40.
I want to get it converted into local timezone in 24 hour format i.e. "IST" in same format i.e. 2021-02-24 18:11:40.
I referred many answers on Stackoverflow, but I am not able to get the result in desired format.
How can it be achieved in Python3?
what I linked applied specifically to your question:
from datetime import datetime, timezone
from dateutil.tz import gettz
# the given info:
ist = gettz("Asia/Kolkata")
s = "2021-02-24 12:41:40"
# now parse to datetime and set tzinfo to UTC
dt = datetime.fromisoformat(s).replace(tzinfo=timezone.utc)
# convert to IST time zone
dt = dt.astimezone(ist)
# output to isoformat string, but without time zone info
s = dt.replace(tzinfo=None).isoformat(' ')
print(s)
# 2021-02-24 18:11:40
Solution for Python 3.6.*
datetime = "2021-02-24 12:41:40"
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
utc = datetime.strptime( datetime,'%Y-%m-%d %H:%M:%S')
utc = utc.replace(tzinfo=from_zone)
local = utc.astimezone(to_zone)
localTime = local.replace(tzinfo=None).isoformat(' ')

DynamoDB timestamp attribute stored in string format, should retrieve records within a specified timestamp range

Dynamodb has timestamp attribute which stores date and time "Thu Jan 14 19:55:27 UTC 2021" in String format.
Now, I want to retrieve records which are in between "Thu Jan 11 20:55:27 UTC 2021" and "Thu Jan 13 22:15:27 UTC 2021".
Below is the code:
from datetime import datetime
from boto3.dynamodb.conditions import Attr
def lambda_handler(event, context):
startdatetime=event["startdate"]
enddatetime=event["enddate"]
start=datetime.strptime(startdatetime,"%a %b %d %H:%M:%S UTC %Y")
end=datetime.strptime(enddatetime,"%a %b %d %H:%M:%S UTC %Y")
fe=Attr('timestamp').between(start,end)
response = table.scan(
FilterExpression=fe
)
This is not giving proper set of records as comparision is happening between string and datetime.
Converting Attr() to datetime is not happening.
Below is the code snippet I tried:
fe=datetime.strptime(str(Attr('timestamp')),"%a %b %d %H:%M:%S UTC %Y").between(start, end)
This also didnt help.
Any suggestions on this ?
DynamoDB does string comparisons for the between part it has no actual concept of a datetime, which is why you have to be careful about the way you store your datetime information in the table.
There are basically two ways that are recommended to store the data in for between queries:
ISO8601 in UTC time, so something like this: 2021-02-12T18:50:00.000+00:00
Epoch time, the number of seconds since 1970-01-01T00:00:00.000+00:00
When you query, you also need to normalize the timestamp you want to query for according to these rules, otherwise it won't work.
Bottom line, the way you want to query it doesn't work, because the format doesn't lend itself to between queries when the underlying data structure is a string.

How to convert a UTC date string to timezone aware datetime object in Python3?

I have a UTC format date string represented as :
ds = "2019-06-15 17:18:06 UTC"
I am trying to convert it into a python utc datetime object like this :
d = datetime.strptime(ds,'%Y-%m-%dT%H:%M:%SZ')
However I am getting the following error :
ValueError: time data '2019-06-15 17:18:06 UTC' does not match format '%Y-%m-%dT%H:%M:%SZ'
So what is the correct format to pass, so that I get a datetime object in UTC timezone?
Use format %Y-%m-%d %H:%M:%S %Z
Ex:
import datetime
import pytz
ds = "2019-06-15 17:18:06 UTC"
nDate = datetime.datetime.strptime(ds,'%Y-%m-%d %H:%M:%S %Z')
timezone = pytz.timezone(ds.split()[-1])
d_aware = timezone.localize(nDate)
print(d_aware)
print(d_aware.tzinfo)
Output:
2019-06-15 17:18:06+00:00
UTC
The format string you are currently using doesn't match with the datetime string format which you provided. That's why its throwing error.
datetime.strptime(ds,'%Y-%m-%d %H:%M:%S UTC')

convert string having timezone into to utc datetime object python

I have a timezone aware string like this and would like to convert it to utc timezone. I am using python 3.4 version
My string is like -
2018-05-04T05:22:52.3272611-04:00
I am not able to get much info on converting the given datetime to utc.
That looks like an ISO 8601 string (though with anomalously high precision on the sub-second component); if the fact that you have 7 digits instead of 6 after the decimal point is a typo, you can use dateutil.parser.isoparse on it:
from dateutil.parser import isoparse
from dateutil.tz import UTC
dt = isoparse('2018-05-04T05:22:52.327261-04:00')
dt.astimezone(UTC)
Otherwise you can use dateutil.parser.parse, which is slower but allows for more unusual formats:
from dateutil.parser import parse
from dateutil.tz import UTC
dt = parse('2018-05-04T05:22:52.3272611-04:00')
dt.astimezone(UTC)
You should also use parse if you are not certain what the format will be.

Resources