1

While scraping data from the internet, I am getting a number as a response instead of the date-time string. Below are few example:

1508486400   --  instead of "2017, 20 Oct 10:00:00"
1510974000   --  instead of "2017, 18 Nov 4:00:00"
1388664000   --  instead of "2014, 02 Jan 13:00:00"

I want to convert these number to the corresponding date in the format "dd/mm/yyyy". Though preserving the timezone is not a mandate, but it is good if I could get the string based on the timezone to which my dates belong.

The dates I am trying to extract from the number belongs to "CAT+2:00:00" timezone.

toyo10
  • 121
  • 1
  • 14
  • It's a [timestamp](https://docs.python.org/3.6/library/datetime.html#datetime.date.fromtimestamp)... `datetime.fromtimestamp(1508486400)` -> `datetime.datetime(2017, 10, 20, 9, 0)` – Jon Clements Jan 02 '18 at 12:31
  • @BhargavRao I think this could be a good question as I am not able to find any question on SO which converts epochtime to `datetime` with the time-zone info. Though the question requires some editting – Moinuddin Quadri Jan 02 '18 at 14:08
  • 1
    Sure, @Moinuddin, do edit the post and make it better! Remember that if a question is duplicate, it doesn't necessarily mean that it's a bad post. It will (and should) remain as a signpost pointing towards the target. – Bhargav Rao Jan 02 '18 at 14:11

3 Answers3

4

The time that you are having is the UNIX time (also known as Epoch or POSIX time). You can convert it into the datetime object and then format it as:

>>> from datetime import datetime

>>> my_datetime = datetime.fromtimestamp(1508486400)
>>> my_datetime.strftime('%d/%m/%Y')
'20/10/2017'

Edit: Based on desired time you mentioned, looks like you expect the time to be in "CAT+2:00:00" timezone. In order to do that, you may use pytz module with timezone "Africa/Harare" as:

>>> from datetime import datetime
>>> import pytz

>>> my_datetime = datetime.fromtimestamp(1508486400, tz= pytz.timezone('Africa/Harare'))
# Will hold the date time object as:
# datetime.datetime(2017, 10, 20, 10, 0, tzinfo=<DstTzInfo 'Africa/Harare' CAT+2:00:00 STD>)

>>> my_datetime.strftime('%d/%m/%Y')
'20/10/2017'

You can get the list of all timezones using pytz.all_timezones.

Also take a look at List of tz database time zones wiki.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
1

If you are using time() function it is number of ticks since 12:00am, January 1, 1970.

keramat
  • 4,328
  • 6
  • 25
  • 38
1

you can use utcfromtimestamp() from datetime to convert timestamp to yyyy/mm/dd format:

import datetime

t = "1508486400"
print(datetime.datetime.utcfromtimestamp(int(t)).strftime('%Y-%m-%d'))

if you want to have the time as well, use '%Y-%m-%d %H:%M:%S' in strftime method. this link will help you to get your desired format from strftime

mehrdadep
  • 972
  • 1
  • 15
  • 37