How to Convert a Time into Epoch Time

How to convert a time into epoch time?

Use the mktime(3) function. For example:

struct tm t = {0};  // Initalize to all 0's
t.tm_year = 112; // This is year-1900, so 112 = 2012
t.tm_mon = 8;
t.tm_mday = 15;
t.tm_hour = 21;
t.tm_min = 54;
t.tm_sec = 13;
time_t timeSinceEpoch = mktime(&t);
// Result: 1347764053

How do I convert a date/time to epoch time (unix time/seconds since 1970) in Perl?

This is the simplest way to get unix time:

use Time::Local;
timelocal($second,$minute,$hour,$day,$month-1,$year);

Note the reverse order of the arguments and that January is month 0.
For many more options, see the DateTime module from CPAN.

As for parsing, see the Date::Parse module from CPAN. If you really need to get fancy with date parsing, the Date::Manip may be helpful, though its own documentation warns you away from it since it carries a lot of baggage (it knows things like common business holidays, for example) and other solutions are much faster.

If you happen to know something about the format of the date/times you'll be parsing then a simple regular expression may suffice but you're probably better off using an appropriate CPAN module. For example, if you know the dates will always be in YMDHMS order, use the CPAN module DateTime::Format::ISO8601.


For my own reference, if nothing else, below is a function I use for an application where I know the dates will always be in YMDHMS order with all or part of the "HMS" part optional. It accepts any delimiters (eg, "2009-02-15" or "2009.02.15"). It returns the corresponding unix time (seconds since 1970-01-01 00:00:00 GMT) or -1 if it couldn't parse it (which means you better be sure you'll never legitimately need to parse the date 1969-12-31 23:59:59). It also presumes two-digit years XX up to "69" refer to "20XX", otherwise "19XX" (eg, "50-02-15" means 2050-02-15 but "75-02-15" means 1975-02-15).

use Time::Local;

sub parsedate {
my($s) = @_;
my($year, $month, $day, $hour, $minute, $second);

if($s =~ m{^\s*(\d{1,4})\W*0*(\d{1,2})\W*0*(\d{1,2})\W*0*
(\d{0,2})\W*0*(\d{0,2})\W*0*(\d{0,2})}x) {
$year = $1; $month = $2; $day = $3;
$hour = $4; $minute = $5; $second = $6;
$hour |= 0; $minute |= 0; $second |= 0; # defaults.
$year = ($year<100 ? ($year<70 ? 2000+$year : 1900+$year) : $year);
return timelocal($second,$minute,$hour,$day,$month-1,$year);
}
return -1;
}

How to convert current date to epoch timestamp?

That should do it

import time

date_time = '29.08.2011 11:05:02'
pattern = '%d.%m.%Y %H:%M:%S'
epoch = int(time.mktime(time.strptime(date_time, pattern)))
print epoch

How do I convert 2012-03-02 into unix epoch time in C?

C (POSIX) provides a function for this. Use strptime() to convert the string into a struct tm value. You can then convert the struct tm into time_t using mktime().

How do I convert this time format into epoch in java? Tue Dec 28 16:55:00 GMT+05:30 2021 to Epoch

Alternative solution with java.time.OffsetDateTime

Here's an alternative solution that makes use of java.time keeping all the information of the input String:

public static void main(String[] args) throws IOException {
// input
String dpDate = "Tue Dec 28 16:55:00 GMT+05:30 2021";
// define a formatter with the pattern and locale of the input
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(
"EEE MMM dd HH:mm:ss OOOO uuuu", Locale.ENGLISH);
// parse the input to an OffsetDateTime using the formatter
OffsetDateTime odt = OffsetDateTime.parse(dpDate, dtf);
// receive the moment in time represented by the OffsetDateTime
Instant instant = odt.toInstant();
// extract its epoch millis
long epochMillis = instant.toEpochMilli();
// and the epoch seconds
long epochSeconds = instant.getEpochSecond();
// and print all the values
System.out.println(String.format("%s ---> %d (ms), %d (s)",
odt, epochMillis, epochSeconds));
}

Output:

2021-12-28T16:55+05:30 ---> 1640690700000 (ms), 1640690700 (s)

A LocalDateTime should not be used here, because you may lose the information about the offset and a ZonedDateTime can neither be used due to the input lacking information about a zone like "Asia/Kolkata" or "America/Chicago", it just provides an offset from UTC.

If you simply want to get the epoch millis, you can write a short method:

// define a constant formatter in the desired class
private static final DateTimeFormatter DTF_INPUT =
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(
"EEE MMM dd HH:mm:ss OOOO uuuu", Locale.ENGLISH);



/**
* parses the input, converts to an instant and returns the millis
*/
public static long getEpochMillisFrom(String input) {
return OffsetDateTime.parse(input, DTF_INPUT)
.toInstant()
.toEpochMilli();
}

Convert python datetime to epoch with strftime

If you want to convert a python datetime to seconds since epoch you could do it explicitly:

>>> (datetime.datetime(2012,4,1,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0

In Python 3.3+ you can use timestamp() instead:

>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0

Why you should not use datetime.strftime('%s')

Python doesn't actually support %s as an argument to strftime (if you check at http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior it's not in the list), the only reason it's working is because Python is passing the information to your system's strftime, which uses your local timezone.

>>> datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'

Javascript Convert Date Time string to Epoch

JavaScript dates are internally stored as milliseconds since epoch. You just need to convert it to a number, e.g. with the unary + operator, to get them. Or you can use the .getTime method.

The harder will be parsing your date string. You likely will use a regex to extract the values from your string and pass them into Date.UTC:

var parts = datestring.match(/(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2})/);
return Date.UTC(+parts[3], parts[2]-1, +parts[1], +parts[4], +parts[5]);

This will yield 1354604400000 ms for your example date.

Convert a date format in epoch

This code shows how to use a java.text.SimpleDateFormat to parse a java.util.Date from a String:

String str = "Jun 13 2003 23:11:52.454 UTC";
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz");
Date date = df.parse(str);
long epoch = date.getTime();
System.out.println(epoch); // 1055545912454

Date.getTime() returns the epoch time in milliseconds.



Related Topics



Leave a reply



Submit