python convert timestamp with timezone to datetime - python

dt = "2021-06-10T10:56:58.189+0200"
is my timestamp, which i want to convert into a datetime representation.
I use following code to do this:
d = dateutil.parser.parse(dt)
But my output looks like this:
2021-06-10 10:56:58.189000+02:00
Not much has changed. How can I include the information about the timezone in my newly created datetime object. I tried out a few more things from the documentation but can not work it out on my own..
Thanks in advance.

note that +0200 is a UTC offset, not a time zone ("America/Los_Angeles" is a time zone for example). If you wish to set a specific time zone, you can do it like
from datetime import datetime
from zoneinfo import ZoneInfo
# you can do the parsing with the standard lib:
s = "2021-06-10T10:56:58.189+0200"
dt = datetime.strptime(s, "%Y-%m-%dT%H:%M:%S.%f%z")
# now set a time zone:
dt_tz = dt.astimezone(ZoneInfo("Europe/Berlin"))
print(dt_tz) # __str__ gives you ISO format
# 2021-06-10 10:56:58.189000+02:00
print(dt_tz.strftime("%Y-%m-%dT%H:%M:%S %Z")) # custom format
# 2021-06-10T10:56:58 CEST
print(repr(dt_tz)) # object representation; __repr__
# datetime.datetime(2021, 6, 10, 10, 56, 58, 189000, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))

Related

Convert timezone naive datetime string to UTC datetime (but not using pytz)

We have the need to convert an incoming datetime string into a UTC datetime string. The incoming string is in this format:
'01/28/2022 12:00 AM'
with intended output as:
'2022-01-28T08:00:00Z'
The string has no declared timezone but is supposed to be PST. We'd like to code this in a way that allows for multiple timezones and date string formats. We can get this working using the following code:
from datetime import datetime
import pytz
UTC_TIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
PROVIDER_DATETIME_FORMAT = '%m/%d/%Y %I:%M %p'
PROVIDER_TIMEZONE = 'America/Los_Angeles'
def dt_string_to_utc_converter(datetime_str)
utc_timezone = pytz.utc
pst_timezone = pytz.timezone(PROVIDER_TIMEZONE)
naive_date = datetime.strptime(datetime_str, PROVIDER_DATETIME_FORMAT)
pst_date = pst_timezone.localize(naive_date)
utc_date = pst_date.astimezone(utc_timezone)
utc_date_str = utc_date.strftime(UTC_TIME_FORMAT)
return utc_date_str
However (for reasons I won't get into) we have been asked to not use the pytz library and instead stick to Python's native datetime, and dateutil libraries. Currently we are committed to Python 3.8.
I've tried a number of things things using datetime's strptime and dateutil's parser, but all to dead ends so far. Are there any obvious patterns i am missing?
Thanks
for the record, here's an option using Python 3.9's zoneinfo and Python 3.7's isoformat.
from datetime import datetime
from zoneinfo import ZoneInfo
def to_isoformat(s, tzname, inputformat='%m/%d/%Y %I:%M %p'):
"""
convert an input string "s" representing date/time in format "inputformat" in
time zone "tzname" to UTC and return an ISO format string with Z denoting UTC.
Parameters
----------
s : str
string representing date/time.
tzname : str
IANA time zone name of time zone that s belongs in.
inputformat : str, optional
date/time string format. The default is '%m/%d/%Y %I:%M %p'.
Returns
-------
str
ISO format string, with seconds precision and Z denoting UTC.
"""
# to datetime and set time zone
dt = datetime.strptime(s, inputformat).replace(tzinfo=ZoneInfo(tzname))
# convert to UTC and make ISO format with Z for UTC
return dt.astimezone(ZoneInfo("UTC")).isoformat(timespec='seconds').replace('+00:00', 'Z')
print(to_isoformat('01/28/2022 12:00 AM', 'America/Los_Angeles'))
# 2022-01-28T08:00:00Z
With Python 3.8, you can basically just replace from zoneinfo import ZoneInfo with from dateutil.tz import gettz as ZoneInfo.
Well, after some more digging I managed to find refs here and here that laid out the basics of what I needed. Final code looks like this:
from datetime import datetime
from dateutil import tz, parser, utils
UTC_TIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
PROVIDER_TIMEZONE = 'America/Los_Angeles'
def dt_string_to_utc_converter(datetime_str)
parsed_dt = parser.parse(datetime_str)
localized_dt = utils.default_tzinfo(parsed_dt, tz.gettz(PROVIDER_TIMEZONE))
utc_dt = localized_dt.astimezone(tz.tzutc())
utc_dt_str = utc_dt.strftime(UTC_TIME_FORMAT)

Python convert timestamp to unix

I know these questions have been asked before but I'm struggling to convert a timestamp string to a unix time and figuring out whether the datetime objects are naive or aware
For example, to convert the time "2021-05-19 12:51:47" to unix:
>>> from datetime import datetime as dt
>>> dt_obj = dt.strptime("2021-05-19 12:51:47", "%Y-%m-%d %H:%M:%S")
>>> dt_obj
datetime.datetime(2021, 5, 19, 12, 51, 47)
is dt_obj naive or aware and how would you determine this? The methods on dt_obj such as timetz, tzinfo, and tzname don't seem to indicate anything - does that mean that dt_obj is naive?
Then to get unix:
>>> dt_obj.timestamp()
1621421507.0
However when I check 1621421507.0 on say https://www.unixtimestamp.com then it tells me that gmt for the above is Wed May 19 2021 10:51:47 GMT+0000, ie 2 hours behind the original timestamp?
since Python's datetime treats naive datetime as local time by default, you need to set the time zone (tzinfo attribute):
from datetime import datetime, timezone
# assuming "2021-05-19 12:51:47" represents UTC:
dt_obj = datetime.fromisoformat("2021-05-19 12:51:47").replace(tzinfo=timezone.utc)
Or, as #Wolf suggested, instead of setting the tzinfo attribute explicitly, you can also modify the input string by adding "+00:00" which is parsed to UTC;
dt_obj = datetime.fromisoformat("2021-05-19 12:51:47" + "+00:00")
In any case, the result
dt_obj.timestamp()
# 1621428707.0
now converts as expected on https://www.unixtimestamp.com/:
As long as you don't specify the timezone when calling strptime, you will produce naive datetime objects. You may pass time zone information via %z format specifier and +00:00 added to the textual date-time representation to get a timezone aware datetime object:
from datetime import datetime
dt_str = "2021-05-19 12:51:47"
print(dt_str)
dt_obj = datetime.strptime(dt_str+"+00:00", "%Y-%m-%d %H:%M:%S%z")
print(dt_obj)
print(dt_obj.timestamp())
The of above script is this:
2021-05-19 12:51:47
2021-05-19 12:51:47+00:00
1621428707.0
datetime.timestamp()
Naive datetime instances are assumed to represent local time and this method relies on the platform C mktime() function to perform the conversion.
So using this does automatically apply yours machine current timezone, following recipe is given to calculate timestamp from naive datetime without influence of timezone:
timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

How to convert datetime.time from UTC to different timezone?

I have variable which holds time which is of type datetime.time in UTC, I wanted it to convert to some other timezone.
we can convert timezones in datetime.datetime instance as shown in this SO link - How do I convert local time to UTC in Python?. I am not able to figure out how to convert timezones in datetime.time instances. I can't use astimezone because datetime.time doesn't have this method.
For example:
>>> t = d.datetime.now().time()
>>> t
datetime.time(12, 56, 44, 398402)
>>>
I need 't' in UTC format.
There are four cases:
input datetime.time has tzinfo set (eg OP mentions UTC)
output as non-naive time
output as naive time (tzinfo not set)
input datetime.time has tzinfo not set
output as non-naive time
output as naive time (tzinfo not set)
The correct answer needs to make use of datetime.datetime.timetz() function because datetime.time cannot be built as a non-naive timestamp by calling localize() or astimezone() directly.
from datetime import datetime, time
import pytz
def timetz_to_tz(t, tz_out):
return datetime.combine(datetime.today(), t).astimezone(tz_out).timetz()
def timetz_to_tz_naive(t, tz_out):
return datetime.combine(datetime.today(), t).astimezone(tz_out).time()
def time_to_tz(t, tz_out):
return tz_out.localize(datetime.combine(datetime.today(), t)).timetz()
def time_to_tz_naive(t, tz_in, tz_out):
return tz_in.localize(datetime.combine(datetime.today(), t)).astimezone(tz_out).time()
Example based on OP requirement:
t = time(12, 56, 44, 398402)
time_to_tz(t, pytz.utc) # assigning tzinfo= directly would not work correctly with other timezones
datetime.time(12, 56, 44, 398402, tzinfo=<UTC>)
In case naive timestamp is wanted:
time_to_tz_naive(t, pytz.utc, pytz.timezone('Europe/Berlin'))
datetime.time(14, 56, 44, 398402)
The cases where the time() instance has already tzinfo set are easier because datetime.combine picks up the tzinfo from the passed parameter, so we just need to convert to tz_out.
I would create a temp datetime object, convert the tz, and extract the time again.
import datetime
def time_to_utc(t):
dt = datetime.datetime.combine(datetime.date.today(), t)
utc_dt = datetime_to_utc(dt)
return utc_dt.time()
t = datetime.datetime.now().time()
utc_t = time_to_utc(t)
where, datetime_to_utc is any of the suggestions in the linked question.
Easy way to convert from/to UTC timezone using pytz:
import datetime, pytz
def time_to_utc(naive, timezone="Europe/Istanbul"):
local = pytz.timezone(timezone)
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)
return utc_dt
def utc_to_time(naive, timezone="Europe/Istanbul"):
return naive.replace(tzinfo=pytz.utc).astimezone(pytz.timezone(timezone))
# type(naive) """DateTime"""
# type(timezone) """String"""
Let's assume you need to convert EST time to UTC. Now, first of all, python datetime objects are not timezone aware by default. They take the system time.
So if you create a datetime object by doing:
from datetime import datetime
date = datetime(2022, 4, 28, 18, 0, 0) # or date = datetime.now() or strftime(), there are so many ways
date would not be timezone aware. We can use pytz to make datetimes timezonz aware and then convert between timezones using localize.
import pytz
from datetime import datetime
est = pytz.timezone('Europe/Paris')
utc = pytz.utc
We make the datetime timezone aware first.
est_time = est.localize(date)
then we can change the timezone and get the relvant time as we wish.
utc_time = est_time.astimezone(utc)
The full list of timezone strings are available at:
pytz.all_timezones

Convert UTC datetime string to local datetime

I've never had to convert time to and from UTC. Recently had a request to have my app be timezone aware, and I've been running myself in circles. Lots of information on converting local time to UTC, which I found fairly elementary (maybe I'm doing that wrong as well), but I can not find any information on easily converting the UTC time to the end-users timezone.
In a nutshell, and android app sends me (appengine app) data and within that data is a timestamp. To store that timestamp to utc time I am using:
datetime.utcfromtimestamp(timestamp)
That seems to be working. When my app stores the data, it is being store as 5 hours ahead (I am EST -5)
The data is being stored on appengine's BigTable, and when retrieved it comes out as a string like so:
"2011-01-21 02:37:21"
How do I convert this string to a DateTime in the users correct time zone?
Also, what is the recommended storage for a users timezone information? (How do you typically store tz info ie: "-5:00" or "EST" etc etc ?) I'm sure the answer to my first question might contain a parameter the answers the second.
If you don't want to provide your own tzinfo objects, check out the python-dateutil library. It provides tzinfo implementations on top of a zoneinfo (Olson) database such that you can refer to time zone rules by a somewhat canonical name.
from datetime import datetime
from dateutil import tz
# METHOD 1: Hardcode zones:
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('America/New_York')
# METHOD 2: Auto-detect zones:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
# utc = datetime.utcnow()
utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')
# Tell the datetime object that it's in UTC time zone since
# datetime objects are 'naive' by default
utc = utc.replace(tzinfo=from_zone)
# Convert time zone
central = utc.astimezone(to_zone)
Edit Expanded example to show strptime usage
Edit 2 Fixed API usage to show better entry point method
Edit 3 Included auto-detect methods for timezones (Yarin)
Here's a resilient method that doesn't depend on any external libraries:
from datetime import datetime
import time
def datetime_from_utc_to_local(utc_datetime):
now_timestamp = time.time()
offset = datetime.fromtimestamp(now_timestamp) - datetime.utcfromtimestamp(now_timestamp)
return utc_datetime + offset
This avoids the timing issues in DelboyJay's example. And the lesser timing issues in Erik van Oosten's amendment.
As an interesting footnote, the timezone offset computed above can differ from the following seemingly equivalent expression, probably due to daylight savings rule changes:
offset = datetime.fromtimestamp(0) - datetime.utcfromtimestamp(0) # NO!
Update: This snippet has the weakness of using the UTC offset of the present time, which may differ from the UTC offset of the input datetime. See comments on this answer for another solution.
To get around the different times, grab the epoch time from the time passed in. Here's what I do:
def utc2local(utc):
epoch = time.mktime(utc.timetuple())
offset = datetime.fromtimestamp(epoch) - datetime.utcfromtimestamp(epoch)
return utc + offset
See the datetime documentation on tzinfo objects. You have to implement the timezones you want to support yourself. The are examples at the bottom of the documentation.
Here's a simple example:
from datetime import datetime,tzinfo,timedelta
class Zone(tzinfo):
def __init__(self,offset,isdst,name):
self.offset = offset
self.isdst = isdst
self.name = name
def utcoffset(self, dt):
return timedelta(hours=self.offset) + self.dst(dt)
def dst(self, dt):
return timedelta(hours=1) if self.isdst else timedelta(0)
def tzname(self,dt):
return self.name
GMT = Zone(0,False,'GMT')
EST = Zone(-5,False,'EST')
print datetime.utcnow().strftime('%m/%d/%Y %H:%M:%S %Z')
print datetime.now(GMT).strftime('%m/%d/%Y %H:%M:%S %Z')
print datetime.now(EST).strftime('%m/%d/%Y %H:%M:%S %Z')
t = datetime.strptime('2011-01-21 02:37:21','%Y-%m-%d %H:%M:%S')
t = t.replace(tzinfo=GMT)
print t
print t.astimezone(EST)
Output
01/22/2011 21:52:09
01/22/2011 21:52:09 GMT
01/22/2011 16:52:09 EST
2011-01-21 02:37:21+00:00
2011-01-20 21:37:21-05:00a
If you want to get the correct result even for the time that corresponds to an ambiguous local time (e.g., during a DST transition) and/or the local utc offset is different at different times in your local time zone then use pytz timezones:
#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz
import tzlocal # $ pip install tzlocal
local_timezone = tzlocal.get_localzone() # get pytz tzinfo
utc_time = datetime.strptime("2011-01-21 02:37:21", "%Y-%m-%d %H:%M:%S")
local_time = utc_time.replace(tzinfo=pytz.utc).astimezone(local_timezone)
This answer should be helpful if you don't want to use any other modules besides datetime.
datetime.utcfromtimestamp(timestamp) returns a naive datetime object (not an aware one). Aware ones are timezone aware, and naive are not. You want an aware one if you want to convert between timezones (e.g. between UTC and local time).
If you aren't the one instantiating the date to start with, but you can still create a naive datetime object in UTC time, you might want to try this Python 3.x code to convert it:
import datetime
d=datetime.datetime.strptime("2011-01-21 02:37:21", "%Y-%m-%d %H:%M:%S") #Get your naive datetime object
d=d.replace(tzinfo=datetime.timezone.utc) #Convert it to an aware datetime object in UTC time.
d=d.astimezone() #Convert it to your local timezone (still aware)
print(d.strftime("%d %b %Y (%I:%M:%S:%f %p) %Z")) #Print it with a directive of choice
Be careful not to mistakenly assume that if your timezone is currently MDT that daylight savings doesn't work with the above code since it prints MST. You'll note that if you change the month to August, it'll print MDT.
Another easy way to get an aware datetime object (also in Python 3.x) is to create it with a timezone specified to start with. Here's an example, using UTC:
import datetime, sys
aware_utc_dt_obj=datetime.datetime.now(datetime.timezone.utc) #create an aware datetime object
dt_obj_local=aware_utc_dt_obj.astimezone() #convert it to local time
#The following section is just code for a directive I made that I liked.
if sys.platform=="win32":
directive="%#d %b %Y (%#I:%M:%S:%f %p) %Z"
else:
directive="%-d %b %Y (%-I:%M:%S:%f %p) %Z"
print(dt_obj_local.strftime(directive))
If you use Python 2.x, you'll probably have to subclass datetime.tzinfo and use that to help you create an aware datetime object, since datetime.timezone doesn't exist in Python 2.x.
If using Django, you can use the timezone.localtime method:
from django.utils import timezone
date
# datetime.datetime(2014, 8, 1, 20, 15, 0, 513000, tzinfo=<UTC>)
timezone.localtime(date)
# datetime.datetime(2014, 8, 1, 16, 15, 0, 513000, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>)
The following worked for me in a Cloud environment for US west:
import datetime
import pytz
#set the timezone
tzInfo = pytz.timezone('America/Los_Angeles')
dt = datetime.datetime.now(tz=tzInfo)
print(dt)
Consolidating the answer from franksands into a convenient method.
import calendar
import datetime
def to_local_datetime(utc_dt):
"""
convert from utc datetime to a locally aware datetime according to the host timezone
:param utc_dt: utc datetime
:return: local timezone datetime
"""
return datetime.datetime.fromtimestamp(calendar.timegm(utc_dt.timetuple()))
You can use arrow
from datetime import datetime
import arrow
now = datetime.utcnow()
print(arrow.get(now).to('local').format())
# '2018-04-04 15:59:24+02:00'
you can feed arrow.get() with anything. timestamp, iso string etc
You can use calendar.timegm to convert your time to seconds since Unix epoch and time.localtime to convert back:
import calendar
import time
time_tuple = time.strptime("2011-01-21 02:37:21", "%Y-%m-%d %H:%M:%S")
t = calendar.timegm(time_tuple)
print time.ctime(t)
Gives Fri Jan 21 05:37:21 2011 (because I'm in UTC+03:00 timezone).
import datetime
def utc_str_to_local_str(utc_str: str, utc_format: str, local_format: str):
"""
:param utc_str: UTC time string
:param utc_format: format of UTC time string
:param local_format: format of local time string
:return: local time string
"""
temp1 = datetime.datetime.strptime(utc_str, utc_format)
temp2 = temp1.replace(tzinfo=datetime.timezone.utc)
local_time = temp2.astimezone()
return local_time.strftime(local_format)
utc_tz_example_str = '2018-10-17T00:00:00.111Z'
utc_fmt = '%Y-%m-%dT%H:%M:%S.%fZ'
local_fmt = '%Y-%m-%dT%H:%M:%S+08:00'
# call my function here
local_tz_str = utc_str_to_local_str(utc_tz_example_str, utc_fmt, local_fmt)
print(local_tz_str) # 2018-10-17T08:00:00+08:00
When I input utc_tz_example_str = 2018-10-17T00:00:00.111Z, (UTC +00:00)
then I will get local_tz_str = 2018-10-17T08:00:00+08:00 (My target timezone +08:00)
parameter utc_format is a format determined by your specific utc_tz_example_str.
parameter local_fmt is the final desired format.
In my case, my desired format is %Y-%m-%dT%H:%M:%S+08:00 ( +08:00 timezone). You should construct the format you want.
This worked for me:
from django.utils import timezone
from datetime import timedelta,datetime
ist_time = timezone.now() + timedelta(hours=5,minutes=30)
#second method
ist_time = datetime.now() + timedelta(hours=5,minutes=30)
I traditionally defer this to the frontend -- send times from the backend as timestamps or some other datetime format in UTC, then let the client figure out the timezone offset and render this data in the proper timezone.
For a webapp, this is pretty easy to do in javascript -- you can figure out the browser's timezone offset pretty easily using builtin methods and then render the data from the backend properly.
From the answer here, you can use the time module to convert from utc to the local time set in your computer:
utc_time = time.strptime("2018-12-13T10:32:00.000", "%Y-%m-%dT%H:%M:%S.%f")
utc_seconds = calendar.timegm(utc_time)
local_time = time.localtime(utc_seconds)
Here is a quick and dirty version that uses the local systems settings to work out the time difference. NOTE: This will not work if you need to convert to a timezone that your current system is not running in. I have tested this with UK settings under BST timezone
from datetime import datetime
def ConvertP4DateTimeToLocal(timestampValue):
assert isinstance(timestampValue, int)
# get the UTC time from the timestamp integer value.
d = datetime.utcfromtimestamp( timestampValue )
# calculate time difference from utcnow and the local system time reported by OS
offset = datetime.now() - datetime.utcnow()
# Add offset to UTC time and return it
return d + offset
Short and simple:
from datetime import datetime
t = "2011-01-21 02:37:21"
datetime.fromisoformat(t) + (datetime.now() - datetime.utcnow())

Converting unix timestamp string to readable date

I have a string representing a unix timestamp (i.e. "1284101485") in Python, and I'd like to convert it to a readable date. When I use time.strftime, I get a TypeError:
>>>import time
>>>print time.strftime("%B %d %Y", "1284101485")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument must be 9-item sequence, not str
Use datetime module:
from datetime import datetime
ts = int('1284101485')
# if you encounter a "year is out of range" error the timestamp
# may be in milliseconds, try `ts /= 1000` in that case
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
>>> from datetime import datetime
>>> datetime.fromtimestamp(1172969203.1)
datetime.datetime(2007, 3, 4, 0, 46, 43, 100000)
Taken from http://seehuhn.de/pages/pdate
The most voted answer suggests using fromtimestamp which is error prone since it uses the local timezone. To avoid issues a better approach is to use UTC:
datetime.datetime.utcfromtimestamp(posix_time).strftime('%Y-%m-%dT%H:%M:%SZ')
Where posix_time is the Posix epoch time you want to convert
>>> import time
>>> time.ctime(int("1284101485"))
'Fri Sep 10 16:51:25 2010'
>>> time.strftime("%D %H:%M", time.localtime(int("1284101485")))
'09/10/10 16:51'
There are two parts:
Convert the unix timestamp ("seconds since epoch") to the local time
Display the local time in the desired format.
A portable way to get the local time that works even if the local time zone had a different utc offset in the past and python has no access to the tz database is to use a pytz timezone:
#!/usr/bin/env python
from datetime import datetime
import tzlocal # $ pip install tzlocal
unix_timestamp = float("1284101485")
local_timezone = tzlocal.get_localzone() # get pytz timezone
local_time = datetime.fromtimestamp(unix_timestamp, local_timezone)
To display it, you could use any time format that is supported by your system e.g.:
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
print(local_time.strftime("%B %d %Y")) # print date in your format
If you do not need a local time, to get a readable UTC time instead:
utc_time = datetime.utcfromtimestamp(unix_timestamp)
print(utc_time.strftime("%Y-%m-%d %H:%M:%S.%f+00:00 (UTC)"))
If you don't care about the timezone issues that might affect what date is returned or if python has access to the tz database on your system:
local_time = datetime.fromtimestamp(unix_timestamp)
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f"))
On Python 3, you could get a timezone-aware datetime using only stdlib (the UTC offset may be wrong if python has no access to the tz database on your system e.g., on Windows):
#!/usr/bin/env python3
from datetime import datetime, timezone
utc_time = datetime.fromtimestamp(unix_timestamp, timezone.utc)
local_time = utc_time.astimezone()
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
Functions from the time module are thin wrappers around the corresponding C API and therefore they may be less portable than the corresponding datetime methods otherwise you could use them too:
#!/usr/bin/env python
import time
unix_timestamp = int("1284101485")
utc_time = time.gmtime(unix_timestamp)
local_time = time.localtime(unix_timestamp)
print(time.strftime("%Y-%m-%d %H:%M:%S", local_time))
print(time.strftime("%Y-%m-%d %H:%M:%S+00:00 (UTC)", utc_time))
In Python 3.6+:
import datetime
timestamp = 1642445213
value = datetime.datetime.fromtimestamp(timestamp)
print(f"{value:%Y-%m-%d %H:%M:%S}")
Output (local time)
2022-01-17 20:46:53
Explanation
Line #1: Import datetime library.
Line #2: Unix time which is seconds since 1970-01-01.
Line #3: Converts this to a unix time object, check with: type(value)
Line #4: Prints in the same format as strp. Local time. To print in UTC see example below.
Bonus
To save the date to a string then print it, use this:
my_date = f"{value:%Y-%m-%d %H:%M:%S}"
print(my_date)
To output in UTC:
value = datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)
# 2022-01-17 18:50:52
Other than using time/datetime package, pandas can also be used to solve the same problem.Here is how we can use pandas to convert timestamp to readable date:
Timestamps can be in two formats:
13 digits(milliseconds) -
To convert milliseconds to date, use:
import pandas
result_ms=pandas.to_datetime('1493530261000',unit='ms')
str(result_ms)
Output: '2017-04-30 05:31:01'
10 digits(seconds) -
To convert seconds to date, use:
import pandas
result_s=pandas.to_datetime('1493530261',unit='s')
str(result_s)
Output: '2017-04-30 05:31:01'
For a human readable timestamp from a UNIX timestamp, I have used this in scripts before:
import os, datetime
datetime.datetime.fromtimestamp(float(os.path.getmtime("FILE"))).strftime("%B %d, %Y")
Output:
'December 26, 2012'
You can convert the current time like this
t=datetime.fromtimestamp(time.time())
t.strftime('%Y-%m-%d')
'2012-03-07'
To convert a date in string to different formats.
import datetime,time
def createDateObject(str_date,strFormat="%Y-%m-%d"):
timeStamp = time.mktime(time.strptime(str_date,strFormat))
return datetime.datetime.fromtimestamp(timeStamp)
def FormatDate(objectDate,strFormat="%Y-%m-%d"):
return objectDate.strftime(strFormat)
Usage
=====
o=createDateObject('2013-03-03')
print FormatDate(o,'%d-%m-%Y')
Output 03-03-2013
timestamp ="124542124"
value = datetime.datetime.fromtimestamp(timestamp)
exct_time = value.strftime('%d %B %Y %H:%M:%S')
Get the readable date from timestamp with time also, also you can change the format of the date.
Note that utcfromtimestamp can lead to unexpected results since it returns a naive datetime object. Python treats naive datetime as local time - while UNIX time refers to UTC.
This ambiguity can be avoided by setting the tz argument in fromtimestamp:
from datetime import datetime, timezone
dtobj = datetime.fromtimestamp(1284101485, timezone.utc)
>>> print(repr(dtobj))
datetime.datetime(2010, 9, 10, 6, 51, 25, tzinfo=datetime.timezone.utc)
Now you can format to string, e.g. an ISO8601 compliant format:
>>> print(dtobj.isoformat(timespec='milliseconds').replace('+00:00', 'Z'))
2010-09-10T06:51:25.000Z
Use the following codes, I hope it will solve your problem.
import datetime as dt
print(dt.datetime.fromtimestamp(int("1284101485")).strftime('%Y-%m-%d %H:%M:%S'))
Use datetime.strftime(format):
from datetime import datetime
unixtime = int('1284101485')
# Print with local time
print(datetime.fromtimestamp(unixtime).strftime('%Y-%m-%d %H:%M:%S'))
# Print with UTC time
print(datetime.utcfromtimestamp(unixtime).strftime('%Y-%m-%d %H:%M:%S'))
datetime.fromtimestamp(timestamp): Return the local date corresponding to the POSIX timestamp, such as is returned by time.time().
datetime.utcfromtimestamp(timestamp): Return the UTC datetime corresponding to the POSIX timestamp, with tzinfo None. (The resulting object is naive.)
import datetime
temp = datetime.datetime.fromtimestamp(1386181800).strftime('%Y-%m-%d %H:%M:%S')
print temp
Another way that this can be done using gmtime and format function;
from time import gmtime
print('{}-{}-{} {}:{}:{}'.format(*gmtime(1538654264.703337)))
Output: 2018-10-4 11:57:44
If you are working with a dataframe and do not want the series cannot be converted to class int error. Use the code below.
new_df= pd.to_datetime(df_new['time'], unit='s')
i just successfully used:
>>> type(tstamp)
pandas.tslib.Timestamp
>>> newDt = tstamp.date()
>>> type(newDt)
datetime.date
You can use easy_date to make it easy:
import date_converter
my_date_string = date_converter.timestamp_to_string(1284101485, "%B %d, %Y")
quick and dirty one liner:
'-'.join(str(x) for x in list(tuple(datetime.datetime.now().timetuple())[:6]))
'2013-5-5-1-9-43'

Categories